How to assertThat String is not empty

Armine picture Armine · May 20, 2017 · Viewed 55.3k times · Source

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()))?

Answer

holi-java picture holi-java · May 20, 2017

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