我试图在 RestAssured TestNG 测试中断言,对于 JSON 文件中的每个给定 ReportCodeNbr,都有一个正确的 UID 值。
我能够通过像本示例中那样使用硬编码索引值引用每个 json 部分来成功地做到这一点,但是,部分的顺序可能会改变,这会改变索引值并破坏测试。
如何最好地存储每个部分的 ReportCodeNbr 的所有值,然后断言 UID 是正确的,而不像我的示例中那样使用硬编码索引值?
一位同事建议使用数组,但我不知道如何去做。
包含两个数据对象的部分 JSON 文件:
[
{
"Url": null,
"DataSteward": null,
"ReportAuthor": null,
"ReportKey": "100PercentSponsorFundedFaculty",
"SystemType": null,
"ReportTitle": "Report",
"ReportCodeNbr": "FIN1065",
"PropertyList": null,
"Title": "100 Percent Sponsor-Funded Faculty",
"Uid": "97d17dbd-9c3b-46aa-ae0e-39603a32250f"
},
{
"Url": null,
"DataSteward": null,
"ReportAuthor": null,
"ReportKey": "2013BaseYearPaidFTEReport",
"SystemType": null,
"ReportTitle": "Report",
"ReportCodeNbr": "FIN1075",
"PropertyList": null,
"Title": "100 Percent Sponsor-Funded Faculty",
"Uid": "97b3f1e0-b17d-448b-86ae-6ed6b432dcd2"
}
]
使用硬编码索引值成功测试:
@Test
public static void firstTest() {
Response response = given().when().get(baseURI);
response.then()
.assertThat().body("ReportCodeNbr[1]", equalTo("FIN1075"))
.assertThat().body("Uid[1]", equalTo("97b3f1e0-b17d-448b-86ae-6ed6b432dcd2"));}
最佳答案
这样的事情应该有效:
Response response = given().when().get(baseURI);
List<String> jsonResponse = response.jsonPath().getList("Uid");
然后,如果您使用的是 >= java 1.8,则可以流式传输该列表并断言它包含您正在查找的值。 否则就使用 for 循环。
有很多方法可以做到这一点。 请参阅此处了解更多信息: Testing Excellence , Rest Assured Docs (jsonPath)
关于java - 在 JAVA 中如何获取 JSON 属性并将其存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58140953/