Java API 接口测试常见有 几种方式,从简单到专业,下面按实际开发中最常用的顺序给你讲,并附示例。
适合:
步骤:
GET / POST / PUT / DELETEhttp://localhost:8080/api/user/1
示例(POST JSON):
{
"name": "Tom",
"age": 18
}
Header:
Content-Type: application/json
适合:
GET 示例:
curl http://localhost:8080/api/user/1
POST 示例:
curl -X POST http://localhost:8080/api/user \
-H "Content-Type: application/json" \
-d '{"name":"Tom","age":18}'
适合:
示例(Spring Boot):
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/api/user/1"))
.andExpect(status().isOk());
}
}
✅ 优点:
适合:
示例:
given()
.contentType(ContentType.JSON)
.when()
.get("/api/user/1")
.then()
.statusCode(200);
依赖:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
如果项目集成了 Swagger:
✅ 访问:
http://localhost:8080/swagger-ui.html
或:
http://localhost:8080/doc.html
直接在网页测试接口,非常方便 ✅
✅ 功能测试
✅ 参数校验
✅ 异常场景
✅ 状态码
✅ 返回数据结构
✅ 权限 / Token
✅ 并发(高级)
| 状态码 | 含义 |
|---|---|
| 200 | 成功 |
| 400 | 参数错误 |
| 401 | 未登录 |
| 403 | 无权限 |
| 404 | 接口不存在 |
| 500 | 服务器异常 |
| 你的角色 | 推荐方式 |
|---|---|
| 后端开发 | JUnit + MockMvc |
| 测试 / 接口联调 | Postman / Swagger |
| 自动化测试 | RestAssured |
| 快速验证 | curl |
如果你愿意,可以告诉我:
我可以直接帮你 写一个完整测试示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。