2013-01-04 127 views
4

我使用Hamcrest Matcher來比較兩個JSON對象。比較方法使用Gson解析器。Hamcrest Matcher with junit style diff

的匹配的偉大工程,但是當兩個JSON是不一樣的,我只能顯示像消息:

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

這是不是非常有幫助,我想展現的元素不匹配,像什麼junit的assertEquals:

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

有沒有辦法實現這一目標?

編輯:

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

但是,這會給我:

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

注意,唯一不同的是 「ID:1」 和 「ID:2」,但JUnit的表明了我JSON中的不同排序也是錯誤的一部分。

回答

2

我能做迄今爲止最好的:

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

這給了我

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],...>