CollectionAssert in jUnit?

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

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

4条回答
  •  感动是毒
    2020-12-02 12:34

    Using JUnit 4.4 you can use assertThat() together with the Hamcrest code (don't worry, it's shipped with JUnit, no need for an extra .jar) to produce complex self-describing asserts including ones that operate on collections:

    import static org.junit.Assert.assertThat;
    import static org.junit.matchers.JUnitMatchers.*;
    import static org.hamcrest.CoreMatchers.*;
    
    List l = Arrays.asList("foo", "bar");
    assertThat(l, hasItems("foo", "bar"));
    assertThat(l, not(hasItem((String) null)));
    assertThat(l, not(hasItems("bar", "quux")));
    // check if two objects are equal with assertThat()
    
    // the following three lines of code check the same thing.
    // the first one is the "traditional" approach,
    // the second one is the succinct version and the third one the verbose one 
    assertEquals(l, Arrays.asList("foo", "bar")));
    assertThat(l, is(Arrays.asList("foo", "bar")));
    assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));
    

    Using this approach you will automagically get a good description of the assert when it fails.

提交回复
热议问题