Java 伪API自动化:断言不起作用
我正在测试一个假的API 这些是以下任务:Java 伪API自动化:断言不起作用,java,api,rest-assured-jsonpath,Java,Api,Rest Assured Jsonpath,我正在测试一个假的API 这些是以下任务: 获取一个随机用户(userID),将其电子邮件地址打印到控制台 使用此用户ID,获取此用户的关联帖子,并验证它们是否包含有效的帖子ID(1到100之间的整数) 使用具有非空标题和正文的同一用户ID发布文章,验证返回了正确的响应(因为这是一个模拟API,它可能不会返回响应代码200,所以请检查文档) 以下是我编写的代码: import io.restassured.http.ContentType; import io.restassured.res
- 获取一个随机用户(userID),将其电子邮件地址打印到控制台
- 使用此用户ID,获取此用户的关联帖子,并验证它们是否包含有效的帖子ID(1到100之间的整数)
- 使用具有非空标题和正文的同一用户ID发布文章,验证返回了正确的响应(因为这是一个模拟API,它可能不会返回响应代码200,所以请检查文档)
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
import org.junit.Assert;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class JsonPlaceHolder {
@Test
public void getUserId() {
Response response = given().when().get("https://jsonplaceholder.typicode.com/users?id=2")
.then().assertThat().statusCode(200).extract().response();
String responseInString = response.asString();
System.out.println(responseInString);
// get the user email address from the response
JsonPath jsonPath = new JsonPath(responseInString);
String emailAddress = jsonPath.getString("email");
System.out.println(emailAddress);
}
@Test
public void userPost() {
Response response = given().contentType(ContentType.JSON).when().get("https://jsonplaceholder.typicode.com/posts?userId=2")
.then().assertThat().statusCode(200).extract().response();
String responseInString = response.asString();
System.out.println(responseInString);
// Using the userID, get the user’s associated posts and
JsonPath jsonPath = new JsonPath(responseInString);
String userPosts = jsonPath.getString("title");
System.out.println(userPosts);
// verify the Posts contain valid Post IDs (an Integer between 1 and 100).
String postId = response.asString();
System.out.println(postId);
**response.then().assertThat().body("id", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(100)));**
}
}
下面是我遇到的断言错误:请建议一些解决方案。谢谢
java.lang.AssertionError:1预期失败。
JSON路径id不匹配。
预期:(等于或大于的值和小于或等于的值)
实际值:[11、12、13、14、15、16、17、18、19、20]您的主要错误在于主体中的id字段实际上是一个数组,而不是单个值,因此将
allOf
匹配器应用于数组而不是每个单独的值,并导致错误
基本上,您需要在以下情况之前链接匹配器:
response.then().assertThat().body("id", everyItem(allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(100))));
你到底在问什么?你有没有看到你正在检查的结果?看起来像是一个整数列表。我在这一行得到了错误。response.then().assertThat().body(“id”,allOf(大于或等于1,小于或等于100));谢谢,@maio290。我已经完成了以下操作,错误消失了。response.then().assertThat().body(“id”,everyItem(大于或等于1));response.then().assertThat().body(“id”,everyItem(lessThanOrEqualTo(100));还有其他短方法来做这个断言吗?你仍然可以使用allOf matcher吗?