Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert that a list is not empty in JUnit

Tags:

junit

junit4

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.

like image 893
Renaud is Not Bill Gates Avatar asked Feb 17 '16 10:02

Renaud is Not Bill Gates


People also ask

How do you check if an assert is empty list?

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.

How do you assert an empty object in JUnit?

We'll use the isEmpty method from the String class along with the Assert class from JUnit to verify whether a given String isn't empty. Since the isEmpty method returns true if the input String is empty we can use it together with the assertFalse method: assertFalse(text.

How do you assert an empty array list?

ArrayList isEmpty() method returns true if list contains no element. In other words, method returns true if list is empty. Else isEmpty() method returns false. In given example, we have first initialized a blank arraylist and checked if it is empty.


2 Answers

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; 
like image 163
JB Nizet Avatar answered Sep 21 '22 02:09

JB Nizet


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;

like image 36
LazerBanana Avatar answered Sep 20 '22 02:09

LazerBanana