Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest Matcher with junit style diff

I am using Hamcrest Matcher to compare two JSON objects. The compare method uses Gson parser.

The matcher works great but when the two JSON are not same, i am only able to show message like:

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

which is not very helpful, i would like to show which elements do not match, something like what junit's assertEquals:

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

Is there a way to achieve that?

EDIT:

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

But this would give me:

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

Notice that the only difference is in "id:1" and "id:2" but junit shows me different ordering in JSON as part of the error as well.

like image 971
rpatali Avatar asked Nov 03 '22 07:11

rpatali


1 Answers

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);
  }
}

This 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],...>
like image 189
rpatali Avatar answered Nov 09 '22 08:11

rpatali