javaunit-testingassertj

AssertJ JSON property check


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");

Solution

  • 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.