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");
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");
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.
If you want to do any serious assertions on JSON object, I would recommend JsonUnit https://github.com/lukas-krecan/JsonUnit
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");
}
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");
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);
© 2022 - 2024 — McMap. All rights reserved.
assertThat()
method is in? Can't see this in JUnit 3.8.1. – Sporangiumorg.json.JSONObject
– Bereniceorg.assertj.core.api.Assertions
API – Berenice