![](/img/trans.png)
[英]Java and OpenAPI - return different payload depend on the response code
[英]Validate OpenAPI response in java
我正在用 Java 进行 OpenAPI 3.x 测试,我想测试和验证来自服务器的响应。
到目前为止,我发现有一个库 Rest Assured 可以用于 API 测试。 我设法使用 JUnit 测试来测试和验证我的简单响应,例如 GET 状态。
我发送 GET 请求并检查状态代码和内容类型等...但我还想检查来自服务器的响应是否具有正确的答案和数据类型。 给定我在 .yml 中的 OpenAPI 规范,例如:
"class_name": "8A",
"count": 4,
"students_in_class": [
{
"id": "s0001",
"first_name": "Jack",
"last_name": "London",
"gender": "male",
"age": 10,
"marks": {
"mathematics": 70,
"science": 84
}
},
在来自服务器的响应正文中,我想检查响应的数据类型,例如我想查看“first_name”是否确实是 String 类型而“age”是否是 Integer 类型。
这是否可以使用 Java 中的 Rest Assured 或是否有任何其他方法可以在 Java 中测试 OpenAPI,因为我想连接 Gitlab 管道 CD/CI 中的 API 测试测试,以便我始终检查我的 OpenAPI 是否良好。
我希望有人能回答我。
将此库添加到您的项目中,然后声明 json 模式。
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.3.1</version>
</dependency>
将架构放入文件中:例如api-schema.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"class_name": {
"type": "string"
},
"count": {
"type": "integer"
},
"students_in_class": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
},
"gender": {
"type": "string"
},
"age": {
"type": "integer"
},
"marks": {
"type": "object",
"properties": {
"mathematics": {
"type": "integer"
},
"science": {
"type": "string"
}
},
"required": [
"mathematics",
"science"
]
}
},
"required": [
"id",
"first_name",
"last_name",
"gender",
"age",
"marks"
]
}
]
}
},
"required": [
"class_name",
"count",
"students_in_class"
]
}
然后使用matchesJsonSchemaInClasspath()
方法验证它
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
given()...
.then().body(matchesJsonSchemaInClasspath("api-schema.json"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.