Checking that a List is not empty in Hamcrest

前端 未结 5 1066
忘了有多久
忘了有多久 2020-12-12 19:43

I was wondering if anyone knew of a way to check if a List is empty using assertThat() and Matchers?

Best way I could see just use JUnit:

5条回答
  •  既然无缘
    2020-12-12 20:34

    Well there's always

    assertThat(list.isEmpty(), is(false));
    

    ... but I'm guessing that's not quite what you meant :)

    Alternatively:

    assertThat((Collection)list, is(not(empty())));
    

    empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

    The following imports can be used with hamcrest 1.3

    import static org.hamcrest.Matchers.empty;
    import static org.hamcrest.core.Is.is;
    import static org.hamcrest.core.IsNot.*;
    

提交回复
热议问题