rest-assured
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseREST Assured - Quick Reference
REST Assured - 快速参考
Deep Knowledge: Usewith technology:mcp__documentation__fetch_docsfor comprehensive documentation.rest-assured
深度知识:使用工具,指定技术为mcp__documentation__fetch_docs即可获取完整文档。rest-assured
When NOT to Use This Skill
不适用场景
- Unit Tests - Use with Mockito for isolated tests
junit - 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
- 单元测试 - 使用搭配Mockito进行隔离测试
junit - 端到端浏览器测试 - 使用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匹配器
| Matcher | Uso |
|---|---|
| Exact match |
| Not null |
| Collection size |
| String contains |
| 匹配器 | 用途 |
|---|---|
| 精确匹配 |
| 非空 |
| 集合大小 |
| 字符串包含指定内容 |
Anti-Patterns
反模式
| Anti-Pattern | Why It's Bad | Solution |
|---|---|---|
| Hardcoding base URI | Not portable across environments | Use RestAssured.baseURI or config |
| Not setting contentType | Request may fail or be misinterpreted | Always set contentType for POST/PUT |
| Ignoring status codes | Silent failures | Always assert status code |
| Not using path parameters | Hard to read, error-prone | Use {id} placeholders |
| Testing too much in one test | Hard to debug | One endpoint/scenario per test |
| No authentication testing | Security gaps | Test auth headers, tokens |
| Not validating response schema | API contract violations | Use JSON schema validation |
| 反模式 | 问题原因 | 解决方案 |
|---|---|---|
| 硬编码基础URI | 无法在多环境间移植 | 使用RestAssured.baseURI或配置文件 |
| 未设置contentType | 请求可能失败或被错误解析 | 对于POST/PUT请求始终设置contentType |
| 忽略状态码 | 可能出现静默失败 | 始终断言状态码 |
| 不使用路径参数 | 代码可读性差、易出错 | 使用{id}占位符 |
| 单个测试中验证过多内容 | 难以调试 | 每个测试仅针对一个端点/场景 |
| 未测试认证 | 存在安全漏洞 | 测试认证头、令牌等 |
| 未验证响应 schema | 可能违反API契约 | 使用JSON schema验证 |
Quick Troubleshooting
快速故障排除
| Problem | Likely Cause | Solution |
|---|---|---|
| "Connection refused" | Server not running | Start server, verify port |
| "Expected status 200 but was 500" | API error or wrong request | Check server logs, validate request body |
| "Cannot deserialize JSON" | Wrong content type or body format | Verify Content-Type header, check JSON |
| Authentication fails | Missing/wrong token | Check Authorization header |
| Timeout | Slow API or network issue | Increase timeout or investigate performance |
| "Path not found" | Wrong URL or method | Verify 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方法 |