JUnit 4 compare Sets

后端 未结 9 1190
-上瘾入骨i
-上瘾入骨i 2020-12-24 03:59

How would you succinctly assert the equality of Collection elements, specifically a Set in JUnit 4?

9条回答
  •  抹茶落季
    2020-12-24 04:40

    If you want to check whether a List or Set contains a set of specific values (instead of comparing it with an already existing collection), often the toString method of collections is handy:

    String[] actualResult = calltestedmethod();
    assertEquals("[foo, bar]", Arrays.asList(actualResult).toString());
    
    List otherResult = callothertestedmethod();
    assertEquals("[42, mice]", otherResult.toString());
    

    This is a bit shorter than first constructing the expected collection and comparing it with the actual collection, and easier to write and correct.

    (Admittedly, this is not a particularily clean method, and can't distinguish an element "foo, bar" from two elements "foo" and "bar". But in practice I think it's most important that it's easy and fast to write tests, otherwise many developers just won't without being pressed.)

提交回复
热议问题