JUnit 4 compare Sets

后端 未结 9 1182
-上瘾入骨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:53

    with hamcrest:

    assertThat(s1, is(s2));
    

    with plain assert:

    assertEquals(s1, s2);
    

    NB:t the equals() method of the concrete set class is used

    0 讨论(0)
  • 2020-12-24 04:55

    As an additional method that is array based ... you can consider using unordered array assertions in junitx . Although the Apache CollectionUtils example will work, there is a pacakge of solid assertion extensions there as well :

    I think that the

    ArrayAssert.assertEquivalenceArrays(new Integer[]{1,2,3}, new Integer[]{1,3,2});
    

    approach will be much more readable and debuggable for you (all Collections support toArray(), so it should be easy enough to use the ArrayAssert methods.

    Of course the downside here is that, junitx is an additional jar file or maven entry...

     <dependency org="junit-addons" name="junit-addons" rev="1.4"/>
    
    0 讨论(0)
  • 2020-12-24 05:03

    Check this article. One example from there:

    @Test  
    public void listEquality() {  
        List<Integer> expected = new ArrayList<Integer>();  
        expected.add(5);  
    
        List<Integer> actual = new ArrayList<Integer>();  
        actual.add(5);  
    
        assertEquals(expected, actual);  
    }  
    
    0 讨论(0)
提交回复
热议问题