skyscreamer/JSONassert

No detailed message when comparison of JSONString fails

vkorobkov opened this issue · 1 comments

When two JSONString objects are compared with org.skyscreamer.jsonassert.JSONCompare#compareJson
then org.skyscreamer.jsonassert.JSONCompareResult does not have an error message with actual/expected values.

That results with unclear failures of unit tests(in my example it is junit 5):
image

The only option for me was to debug when I wanted to get the actual/expected values mismatch.

How to reproduce with JUnit and Groovy:

@Test
void testJsonAssert() {
    JSONAssert.assertEquals('"EXPECTED"', '"ACTUAL"', true)
}

Cheers

I found a temporary dirty workaround for Spring + MockMvc + Groovy kind of tests:

  1. Extend ResultActions with a custom matcher using groovy extension methods
static ResultActions andExpectJson(ResultActions resultAction, Object expectedObject) {
        def expected = new ObjectMapper().writeValueAsString(body: expectedObject)
        resultAction
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            // todo: .andExpect(content().json(json)) when see https://github.com/skyscreamer/JSONassert/issues/101 is done
            .andExpect({ MvcResult result ->
                def actual = result.response.contentAsString
                JSONAssert.assertEquals(expected, """{ "body": $actual }""", true)
            })
    }

This matcher adds a dummy root element("body") for expected/actual JSON, so these are not JSONStrings anymore.

  1. And the tests look like
mockMvc
  .perform(request)
  .andExpect(status().isOk())
  .andExpectJson(RegisterByEmail.Result.OK) // calls my custom matcher

Test output became a little more readable:
image