Hamcrest Matcher with junit style diff

I use Hamcrest Matcher to compare two JSON objects. The comparison method uses the Gson parser.

The connector works fine, but when the two JSONs are not the same, I can show the message as:

Expected: <[{"data":"data1","application":{"id":"1"}}]> but: <[{"data":"data1","application":{"id":"2"}}]> 

which is not very useful, I would like to show which elements do not match, something like junit assertEquals:

 expected:<...a1","application":{"[filtered":false,"id":"1"]...> but was:<...a1","application":{"[id":"2"...> 

Is there any way to achieve this?

EDIT:

 @Override protected void describeMismatchSafely(JsonElement item, Description mismatchDescription) { //mismatchDescription.appendValue(item); assertEquals(item.toString(), originalJson.toString()); } 

But that would give me:

 expected:<...a1","application":{"[filtered":false,"id":"2"]...> but was:<...a1","application":{"[id":"1","filtered":false],...> 

Note that the only difference is "id: 1" and "id: 2", but junit shows me another ordering in JSON as part of the error.

+4
source share
1 answer

The best I could do so far:

 @Override protected void describeMismatchSafely(JsonElement expectedJson, Description mismatchDescription) { mismatchDescription.appendValue(expectedJson).appendText("\ndifference:\n"); try { assertEquals(expectedJson.toString(), originalJson.toString()); } catch (ComparisonFailure e) { String message = e.getMessage(); message = message.replace("expected:", ""); message = message.replace("but was:", ""); message = message.replaceFirst(">", ">\n"); mismatchDescription.appendText(message); } } 

It gives me

 Expected: <[{"data":"data1","application":{"id":"1"}}]> but: <[{"data":"data1","application":{"id":"2"}}]> difference: <...a1","application":{"[filtered":false,"id":"2"],...> <...a1","application":{"[id":"1","filtered":false],...> 
+2
source

All Articles