skyscreamer / JSONassert

Write JSON unit tests in less code. Great for testing REST interfaces.
http://jsonassert.skyscreamer.org
Apache License 2.0
990 stars 198 forks source link

No detailed message when comparison of JSONString fails #101

Open vkorobkov opened 6 years ago

vkorobkov commented 6 years ago

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

vkorobkov commented 6 years ago

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.

  2. 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