3

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I think I solved it some other way but I'll try this out too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.