I have JSONObject instance which contains some property,
{
"name":"testName",
"age":"23"
}
i use the following assert, but it fails. Is this correct approach to test JSON in assertj.
assertThat(jsonObject).hasFieldOrProperty("name");
如果你想对 JSON 对象做任何严肃的断言,我会推荐 JsonUnit https://github.com/lukas-krecan/JsonUnit
I think it has to do with the fact the JSONObject
is like a map which has key-value pairs, while AssertJ expects Java bean-style objects to check if a property exists. I understood this from the document at https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractObjectAssert.html#hasFieldOrProperty(java.lang.String) . Hope I am looking at the right place.
I mean to say that a map or JSONObject
doesn't have fields declared in it for AssertJ to look for.
You may use JSONObject.has( String key )
instead, I think.
Fist, you need to traverse the keysets (nodes) using the map
class, then verify if the keyset contains the particular node you are looking for.
Map<String, Object> read = JsonPath.read(JSONObject, "$");
assertThat(read.keySet()).contains("name");
If you use SpringBoot you can use the custom impl. for Assertj
private final BasicJsonTester json = new BasicJsonTester(getClass());
@Test
void testIfHasPropertyName() {
final JSONObject jsonObject = new JSONObject("{\n" +
"\"name\":\"testName\",\n" +
"\"age\":\"23\"\n" +
"}");
assertThat(json.from(jsonObject.toString())).hasJsonPath( "$.name");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.