views:

118

answers:

3

Hey,

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:

assertFalse(list.isEmpty());

But I was hoping that there was some way to do this in Hamcrest.

Thanks!

+2  A: 

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's wonky generics.

skaffman
I find that Hamcrest code looks much nicer if you change your syntax highlighting to make the parenthesis invisible...
skaffman
Your second assertThat() gives me the following error: The method assertThat(T, Matcher<T>) in the type Assert is not applicable for the arguments (List<Integer>, Matcher<Collection<Object>>)
tkeE2036
@tkeE2036: That's Hamcrest's broken generics at work. Sometimes you need to cast to make it compile, e.g. `assertThat((Collection)list, is(not(empty())));`
skaffman
A: 

Use IsEmptyCollection.empty() matcher. Here is hamcrests unit tests using this. Specifically:

List list = new ArrayList();
assertMatches("empty collection", empty(), list);
krock
A: 

For a better solution, vote for: http://code.google.com/p/hamcrest/issues/detail?id=97

Fabricio Lemos