6

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");
parrotjack
  • 432
  • 1
  • 6
  • 18
  • I'm not sure which JSONObject class you are using. It would be better to provide the full class name including package so that we can help you more precisely. In any case you should consider using JsonUnit to do assertj assertions on json content: https://github.com/lukas-krecan/JsonUnit – Sebastien Jan 21 '20 at 10:37
  • Apart from what @Sebastien has mentioned, can you also mention which library this ```assertThat()``` method is in? Can't see this in JUnit 3.8.1. – Sree Kumar Jan 21 '20 at 10:42
  • My JSONObject class from ```org.json.JSONObject``` – parrotjack Jan 21 '20 at 10:46
  • @SreeKumar i use ```org.assertj.core.api.Assertions``` API – parrotjack Jan 21 '20 at 10:47

4 Answers4

8

If you want to do any serious assertions on JSON object, I would recommend JsonUnit https://github.com/lukas-krecan/JsonUnit

Joel Costigliola
  • 6,308
  • 27
  • 35
3

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

Eugene
  • 117,005
  • 15
  • 201
  • 306
Marious
  • 143
  • 1
  • 11
2

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.

Sree Kumar
  • 2,012
  • 12
  • 9
0

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");
Testilla
  • 602
  • 8
  • 21