How to assertThat String is not empty

Viewed 71648

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

11 Answers

Consider using Apache's StringUtils.isNotEmpty() method, which is a null-safe check for an empty string.

assertTrue(StringUtils.isNotEmpty(str));

You can use the Google Guava Library method Strings.isNullOrEmpty

From the JavaDoc

public static boolean isNullOrEmpty(@Nullable String string)

Returns true if the given string is null or is the empty string.

Consider normalizing your string references with nullToEmpty(java.lang.String). If you do, you can use String.isEmpty() instead of this method, and you won't need special null-safe forms of methods like String.toUpperCase(java.util.Locale) either. Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull(java.lang.String).

Parameters:

string - a string reference to check

Returns:

true if the string is null or is the empty string

Without hamcrest:

    assertFalse(StringUtils.isEmpty(string));

if you're using JUnit5 then you can use assertNotNull("yourString"); to assert if your String is not empty or null .

alternatively if you need a message then you can use

assertNotNull("your String", "String is empty");
Related