2014年4月4日 星期五

Junit - 如何比較JsonArray是否相同?

參考:http://stackoverflow.com/questions/2253750/compare-two-json-objects-in-java

好久沒寫blog了,這陣子還是忙到昏天地暗,但也寫了一些HttpUnit的練習,有機會再來分享:)

json是很常使用的格式,我自己的專案也大量的運用它來傳遞訊息,那麼,如何比較兩個jsonArray是否相等呢?(或json)

用junit的assertEquals()是無法正確比較其中內容的,因此我們需要額外的方式:

  1. 下載JSONassert From Maven
  2. 使用:
    JSONAssert.assertEquals(expected,actual,false);
上述的第三個參數:boolean strict,說明,可參考doc上所寫:

There are two modes, strict and non-strict. In most cases, you will probably want to set strict to false, since that will make the tests less brittle.
Strict tests require all of the elements requested to be returned, and only those elements (ie, the tests are non-extensible). Arrays of elements must be returned in the same order as expected. For example, say I'm expecting:
{id:123,things['a','b','c']}The following would match when doing non-strict checking, but would fail on strict checking:
{id:123,things['c','b','a'],anotherfield:'blah'}

何時該使用strict(==true)就端看個人需求選擇囉~

沒有留言:

張貼留言