parrotjack
parrotjack

Reputation: 512

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

Upvotes: 8

Views: 18954

Answers (5)

Michael Böckling
Michael Böckling

Reputation: 7862

Spring Boot has a dependency on JSONAssert that you can use:

import static org.skyscreamer.jsonassert.JSONAssert.assertEquals;

var actual = ...
var expected = """
    {
    "property": "value"
    }
    """
assertEquals(expected, actual, false);

Upvotes: 0

Marious
Marious

Reputation: 171

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

Upvotes: 5

Testilla
Testilla

Reputation: 692

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

Upvotes: 0

Joel Costigliola
Joel Costigliola

Reputation: 7066

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

Upvotes: 9

Sree Kumar
Sree Kumar

Reputation: 2245

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.

Upvotes: 4

Related Questions