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()))
?
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.
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.
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
You can use JUnit's own assertNotEquals
assertion:
Assert.assertNotEquals( "", string );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With