rest-assured

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

REST Assured - Quick Reference

REST Assured - 快速参考

Deep Knowledge: Use
mcp__documentation__fetch_docs
with technology:
rest-assured
for comprehensive documentation.
深度知识:使用
mcp__documentation__fetch_docs
工具,指定技术为
rest-assured
即可获取完整文档。

When NOT to Use This Skill

不适用场景

  • Unit Tests - Use
    junit
    with Mockito for isolated tests
  • E2E Browser Tests - Use Selenium or Playwright
  • WebSocket Testing - Use dedicated WebSocket testing tools
  • Non-Java Projects - Use language-specific HTTP clients
  • GraphQL APIs - Consider GraphQL-specific testing tools
  • 单元测试 - 使用
    junit
    搭配Mockito进行隔离测试
  • 端到端浏览器测试 - 使用Selenium或Playwright
  • WebSocket测试 - 使用专用的WebSocket测试工具
  • 非Java项目 - 使用对应语言的HTTP客户端
  • GraphQL API - 考虑使用GraphQL专用测试工具

Pattern Essenziali

核心模式

GET Request

GET 请求

java
given()
    .baseUri("http://localhost:8080")
    .contentType("application/json")
.when()
    .get("/api/v1/users/1")
.then()
    .statusCode(200)
    .body("name", equalTo("John"));
java
given()
    .baseUri("http://localhost:8080")
    .contentType("application/json")
.when()
    .get("/api/v1/users/1")
.then()
    .statusCode(200)
    .body("name", equalTo("John"));

POST Request

POST 请求

java
given()
    .contentType("application/json")
    .body("""
        {"name": "John", "email": "john@example.com"}
        """)
.when()
    .post("/api/v1/users")
.then()
    .statusCode(201)
    .body("id", notNullValue());
java
given()
    .contentType("application/json")
    .body("""
        {"name": "John", "email": "john@example.com"}
        """)
.when()
    .post("/api/v1/users")
.then()
    .statusCode(201)
    .body("id", notNullValue());

Spring Boot Integration

Spring Boot 集成

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserApiTest {
    @LocalServerPort
    private int port;

    @BeforeEach
    void setUp() {
        RestAssured.port = port;
    }

    @Test
    void shouldGetUsers() {
        given()
        .when().get("/api/v1/users")
        .then().statusCode(200);
    }
}
java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserApiTest {
    @LocalServerPort
    private int port;

    @BeforeEach
    void setUp() {
        RestAssured.port = port;
    }

    @Test
    void shouldGetUsers() {
        given()
        .when().get("/api/v1/users")
        .then().statusCode(200);
    }
}

Authentication

认证

java
// Bearer Token
given().header("Authorization", "Bearer " + token)

// Basic Auth
given().auth().basic("user", "pass")
java
// Bearer Token
given().header("Authorization", "Bearer " + token)

// 基础认证
given().auth().basic("user", "pass")

Hamcrest Matchers Comuni

常用Hamcrest匹配器

MatcherUso
equalTo(value)
Exact match
notNullValue()
Not null
hasSize(n)
Collection size
containsString(str)
String contains
匹配器用途
equalTo(value)
精确匹配
notNullValue()
非空
hasSize(n)
集合大小
containsString(str)
字符串包含指定内容

Anti-Patterns

反模式

Anti-PatternWhy It's BadSolution
Hardcoding base URINot portable across environmentsUse RestAssured.baseURI or config
Not setting contentTypeRequest may fail or be misinterpretedAlways set contentType for POST/PUT
Ignoring status codesSilent failuresAlways assert status code
Not using path parametersHard to read, error-proneUse {id} placeholders
Testing too much in one testHard to debugOne endpoint/scenario per test
No authentication testingSecurity gapsTest auth headers, tokens
Not validating response schemaAPI contract violationsUse JSON schema validation
反模式问题原因解决方案
硬编码基础URI无法在多环境间移植使用RestAssured.baseURI或配置文件
未设置contentType请求可能失败或被错误解析对于POST/PUT请求始终设置contentType
忽略状态码可能出现静默失败始终断言状态码
不使用路径参数代码可读性差、易出错使用{id}占位符
单个测试中验证过多内容难以调试每个测试仅针对一个端点/场景
未测试认证存在安全漏洞测试认证头、令牌等
未验证响应 schema可能违反API契约使用JSON schema验证

Quick Troubleshooting

快速故障排除

ProblemLikely CauseSolution
"Connection refused"Server not runningStart server, verify port
"Expected status 200 but was 500"API error or wrong requestCheck server logs, validate request body
"Cannot deserialize JSON"Wrong content type or body formatVerify Content-Type header, check JSON
Authentication failsMissing/wrong tokenCheck Authorization header
TimeoutSlow API or network issueIncrease timeout or investigate performance
"Path not found"Wrong URL or methodVerify endpoint exists, check HTTP method
问题可能原因解决方案
"Connection refused"(连接被拒绝)服务器未启动启动服务器,验证端口是否正确
"Expected status 200 but was 500"(预期状态码200,实际为500)API错误或请求有误查看服务器日志,验证请求体
"Cannot deserialize JSON"(无法反序列化JSON)内容类型或请求体格式错误验证Content-Type头,检查JSON格式
认证失败令牌缺失或错误检查Authorization头
超时API响应慢或网络问题增加超时时间或排查性能问题
"Path not found"(路径未找到)URL或请求方法错误验证端点是否存在,检查HTTP方法

Reference Documentation

参考文档