71

I want to assert that a list is not empty in JUnit 4, when I googled about it I found this post : Checking that a List is not empty in Hamcrest which was using Hamcrest.

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

which gives me this error :

The method is(boolean) is undefined for the type MaintenanceDaoImplTest

how can I do that without using Hamcrest.

Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • See also here http://stackoverflow.com/questions/3631110/checking-that-a-list-is-not-empty-in-hamcrest – Florian Schaetz Feb 17 '16 at 10:41
  • Just for reference: `assertThat(items, IsCollectionWithSize.hasSize(greaterThan(1)))` checks the size of the collection. But unfortunately it doesn't print items in the collection in case of failure :( – Ilya Serbis Sep 17 '20 at 20:52

7 Answers7

125

You can simply use

assertFalse(result.isEmpty());

Regarding your problem, it's simply caused by the fact that you forgot to statically import the is() method from Hamcrest;

import static org.hamcrest.CoreMatchers.is;
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
41

This reads quite nicely and uses Hamcrest. Exactly what you asked for ;) Always nice when the code reads like a comment.

assertThat(myList, is(empty()));
assertThat(myList, is(not(empty())));

You can add is as a static import to your IDE as I know that eclipse and IntelliJ is struggling with suggesting it even when it is on the classpath.


IntelliJ

Settings -> Code Style -> Java -> Imports 

Eclipse

Prefs -> Java -> Editor -> Content Assist -> Favourites 

And the import itself is import static org.hamcrest.CoreMatchers.is;

LazerBanana
  • 6,865
  • 3
  • 28
  • 47
5

You can check if your list is not equal an Empty List (Collections.EMPTY_LIST), try this:

Assertions.assertNotEquals(Collections.EMPTY_LIST, yourList);
phoenixstudio
  • 1,776
  • 1
  • 14
  • 19
1

I like to use

Assert.assertEquals(List.of(), result)

That way, you get a really good error message if the list isn't empty. E.g.

java.lang.AssertionError: 
Expected :[]
Actual   :[something unexpected]
Harry
  • 187
  • 2
  • 10
1

assertEquals(Collections.Empty_List,Collections.emptyList())

Try this.

Arindam
  • 675
  • 8
  • 15
-2

I was also looking for something similar, but the easiest work around can be

Assert.AreEqual(result.Count, 0);

When the collection has no records.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sahil
  • 9
  • 3
-2

You can change "is" to "equalTo": assertThat(result.isEmpty(), equalTo(false));