问题描述
我正在放心使用几年前使用过的东西。这样做时,我在项目中有一个包含Json文件的文件夹。我将这些与API响应的实际结果进行了比较。最好的方法是什么。我显然需要项目中的文件位置,并且需要将其与我的响应进行比较。有标准的方法可以做到这一点。
所以最初我有这个。只是从身体上检查城市,但我想要整个东西。
@Test
public void GetCity() {
given().
when().
get(city).
then().
assertthat().
body(("city"),equalTo(city));
}
但是我想在下面找到类似的东西:
@Test
public void GetCity() {
given().
when().
get(city).
then().
assertthat().
JsonFile(("/Myjson"),equalTo(response));
}
我目前正在使用TestNg,但我记得使用了黄瓜方案,该方案使我能够测试数据表中的多个响应。我的问题是如何实现以上目标?
{
"id": 25,"first_name": "Caryl","last_name": "RuBerry","email": "cruBerry[email protected]","ip_address": "222.10.201.47","latitude": 11.8554828,"longitude": -86.2183907,"city": "Dolores"
}
解决方法
我从这个问题中了解到的是从API获取响应并与JSON文件进行比较。怎么做:
@Test
public void GetCity() {
Response response = when().
get(city).
then().
extract()
response();
}
首先,我们提取Response
对象,其中包含诸如状态码或响应正文之类的信息。在这种情况下,它将是JSON。在提取它之前,让我们创建一个具有JSON表示形式的POJO:
{
"id": 25,"first_name": "Caryl","last_name": "Ruberry","email": "[email protected]","ip_address": "222.10.201.47","latitude": 11.8554828,"longitude": -86.2183907,"city": "Dolores"
}
上述JSON可以由以下类表示:
public class UserEntity {
public Long id; //id is exact name field in JSON
@JsonProperty("first_name"); //other approach
public String firstName;
public String last_name;
public String email;
public String ip_address;
public Long latitude;
public Long longitude;
public String city;
}
现在,我们可以像这样将JSON响应主体转换为此类:
@Test
public void GetCity() {
Response response = when().
get(city).
then().
extract()
response();
UserEntity userEntityResponse = response.jsonPath().getObject("$",UserEntity.class);
}
“ $”表示JSON文件的根(第一个对象{})。这就是将Response转换为POJO的方式。我们可以通过非常相似的方式做到这一点
Response response = when().
get(city).
then().
extract()
response();
UserEntity userEntityResponse = response.jsonPath().getObject("$",UserEntity.class);
UserEntity userEntityFile = JsonPath.from(new File("file path"));
现在,您可以轻松地将它们进行比较,例如:
assertEquals(userEntityFile.id,userEntityResponse.id);
您还可以覆盖hashCode()
和equals()
方法,但是如果您只是在学习:)