CollectionAssert in jUnit?

前端 未结 4 985
臣服心动
臣服心动 2020-12-02 12:13

Is there a jUnit parallel to NUnit\'s CollectionAssert?

4条回答
  •  执念已碎
    2020-12-02 12:40

    Joachim Sauer's solution is nice but doesn't work if you already have an array of expectations that you want to verify are in your result. This might come up when you already have a generated or constant expectation in your tests that you want to compare a result to, or perhaps you have multiple expectations you expect to be merged in the result. So instead of using matchers you can can just use List::containsAll and assertTrue For Example:

    @Test
    public void testMerge() {
        final List expected1 = ImmutableList.of("a", "b", "c");
        final List expected2 = ImmutableList.of("x", "y", "z");
        final List result = someMethodToTest(); 
    
        assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK
        assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK
    
        assertTrue(result.containsAll(expected1));  // works~ but has less fancy
        assertTrue(result.containsAll(expected2));  // works~ but has less fancy
    }
    

提交回复
热议问题