Enoobong
Enoobong

Reputation: 1734

Matching object in JSON with jsonpath in Spring Boot Test

I'm trying to write unit tests for a rest endpoint with Spring Boot Test that's going well but when I try to assert on an object in the json response with jsonPath an AssertionError is thrown even when contents are identical and the same.

Sample Json

{
"status": 200,
"data": [
    {
        "id": 1,
        "placed_by": 1,
        "weight": 0.1,
        "weight_metric": "KG",
        "sent_on": null,
        "delivered_on": null,
        "status": "PLACED",
        "from": "1 string, string, string, string",
        "to": "1 string, string, string, string",
        "current_location": "1 string, string, string, string"
    }
]

}

Code in Kotlin

mockMvc.perform(
        get("/api/v1/stuff")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
    ).andExpect(status().isOk)
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
        .andExpect(jsonPath("\$.status").value(HttpStatus.OK.value()))
        .andExpect(jsonPath("\$.data.[0]").value(equalTo(stuffDTO.asJsonString())))

That throws AssertionError but the values are the same Assertion Error Log

Clicking on see difference says

enter image description here

How can I match an object in JSON with jsonPath? I need to be able to match an object because the object can contain many fields and it will be a PITA to match them individually

Upvotes: 3

Views: 9366

Answers (1)

WonkySpecs
WonkySpecs

Reputation: 11

I came across what looks like the same issue, though it's hard to say without knowing what your asJsonString function is. Also I was using Java, not Kotlin. If it is the same issue:

It's due to jsonPath(expression) not returning a string, so matching it with one doesn't work. You need to convert stuffDTO into the correct type for matching using JsonPath ie. in a function such as:

private <T> T asParsedJson(Object obj) throws JsonProcessingException {
    String json = new ObjectMapper().writeValueAsString(obj);
    return JsonPath.read(json, "$");
}

Then .andExpect(jsonPath("\$.data.[0]").value(equalTo(asParsedJson(stuffDTO)))) should work.

Upvotes: 1

Related Questions