用更少的代码编写 JSON 单元测试。非常适合测试 REST 接口。
像比较字符串一样编写 JSON 测试。JSONassert 将您的字符串转换为 JSON 对象,并将逻辑结构和数据与实际的 JSON 进行比较。当strict设置为 false
(推荐)时,它允许重新排序数据和扩展结果(只要所有预期的元素都存在),从而使测试不那么脆弱。
支持的测试框架:JUnit
代码示例
在 JSONassert 中,您编写和维护如下内容:
JSONObject data = getRESTData("/friends/367.json");
String expected = "{friends:[{id:123,name:\"Corby Page\"},{id:456,name:\"Carter Page\"}]}";
JSONAssert.assertEquals(expected, data, false);
而不是这一切:
JSONObject data = getRESTData("/friends/367.json");
Assert.assertTrue(data.has("friends"));
Object friendsObject = data.get("friends");
Assert.assertTrue(friendsObject instanceof JSONArray);
JSONArray friends = (JSONArray) friendsObject;
Assert.assertEquals(2, friends.length());
JSONObject friend1Obj = friends.getJSONObject(0);
Assert.assertTrue(friend1Obj.has("id"));
Assert.assertTrue(friend1Obj.has("name"));
JSONObject friend2Obj = friends.getJSONObject(1);
Assert.assertTrue(friend2Obj.has("id"));
Assert.assertTrue(friend2Obj.has("name"));
if ("Carter Page".equals(friend1Obj.getString("name"))) {
Assert.assertEquals(456, friend1Obj.getInt("id"));
Assert.assertEquals("Corby Page", friend2Obj.getString("name"));
Assert.assertEquals(123, friend2Obj.getInt("id"));
}
else if ("Corby Page".equals(friend1Obj.getString("name"))) {
Assert.assertEquals(123, friend1Obj.getInt("id"));
Assert.assertEquals("Carter Page", friend2Obj.getString("name"));
Assert.assertEquals(456, friend2Obj.getInt("id"));
}
else {
Assert.fail("Expected either Carter or Corby, Got: " + friend1Obj.getString("name"));
}
错误信息
我们试图使错误消息易于理解。这非常重要,因为肉眼很难分辨出差异,尤其是在长 JSON 字符串中。例如:
String expected = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}";
String actual = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"cat\",\"fish\"]}],pets:[]}"
JSONAssert.assertEquals(expected, actual, false);
返回以下内容:
friends[id=3].pets[]: Expected bird, but not found ; friends[id=3].pets[]: Contains cat, but not expected
它告诉您 id=3 的 friend 下的 pets 数组应该包含“bird”,但却包含“cat”。(也许猫吃了鸟?)
快速开始
将以下内容添加到项目的 pom.xml 中:
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
像这样编写测试:
JSONAssert.assertEquals(expectedJSONString, actualJSON, strictMode);
更多示例:
http://jsonassert.skyscreamer.org/cookbook.html?ref=morioh.com&utm_source=morioh.com
github地址:
https://github.com/skyscreamer/JSONassert
除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/2785.html
暂无评论