Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assertThat String is not empty

Asserting that a string is not empty in junit can be done in the following ways:

 assertTrue(!string.isEmpty());  assertFalse(string.isEmpty());  assertThat(string.toCharArray(), is(not(emptyArray())); // (although this didn't compile) 

My question is: is there a better way of checking this - something like:

assertThat(string, is(not(empty()))?

like image 520
Armine Avatar asked May 20 '17 14:05

Armine


People also ask

How do you assert not null in JUnit?

Assert class in case of JUnit 4 or JUnit 3 to assert using assertNotNull method. Assertions. assertNotNull() checks if object is not null. In case, object is null, it will through AssertError.

Is empty in Nunit?

IsEmpty may be used to test either a string or a collection or IEnumerable. When used with a string, it succeeds if the string is the empty string. When used with a collection, it succeeds if the collection is empty.


2 Answers

In hamcrest 1.3 you can using Matchers#isEmptyString :

assertThat(string, not(isEmptyString())); 

In hamcrest 2.0 you can using Matchers#emptyString :

assertThat(string, is(not(emptyString()))); 

UPDATE - Notice that : "Maven central has some extra artifacts called java-hamcrest and hamcrest-java, with a version of 2.0.0.0. Please do not use these, as they are an aborted effort at repackaging the different jars." source : hamcrest.org/JavaHamcrest/distributables

like image 162
holi-java Avatar answered Sep 22 '22 15:09

holi-java


You can use JUnit's own assertNotEquals assertion:

Assert.assertNotEquals( "", string ); 
like image 30
Stefan Birkner Avatar answered Sep 20 '22 15:09

Stefan Birkner