How to assertThat String is not empty
Asked Answered
R

11

45

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

Recalcitrant answered 20/5, 2017 at 14:9 Comment(2)
There is a matcher for those string operations: IsEmptyStringLandau
Another alternative: assertThat(string.isEmpty(), is(false))Landau
T
80

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

Teepee answered 20/5, 2017 at 17:26 Comment(7)
I'd figured there ought to be something like that, but I assumed there must not be or the OP wouldn't have asked. Thanks for actually checking. :-)Pantile
Yeah, but yours is better (or at least, it's what I'd actually use, now that I know it exists).Pantile
@Pantile yes, it can make the test code more readable (we can read the expressiveness test as an article).Teepee
Good answer but beware that the statements return true when the String is null.. Depending on your specs, you might want to add CoreMatchers.notNullValue() to your test.Arathorn
@StevenKuypers yes, sir. but the question is check whether String is empty rather than null or empty. for that there are related matchers, e.g: isEmptyOrNullString() in 1.3 or emptyOrNullString() in 2.0.Teepee
Is there really a "hamcrest 2.0" though ? "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/distributablesMaryannmaryanna
I had to use the hamcrest-all dependency and import static org.hamcrest.text.IsEmptyString.* so that it worked for me. I did bang my head against the wall slightly but I found it.Masterstroke
R
11

What you may also do is use library called AssertJ which provides great fluent assertions into your code. Check can be done with elegant:

assertThat(myString).isNotEmpty();

Recently answered 20/5, 2017 at 14:22 Comment(1)
AssertJ Core site has moved to assertj.github.io/docPaleobotany
R
7

You can use JUnit's own assertNotEquals assertion:

Assert.assertNotEquals( "", string );
Riparian answered 22/5, 2017 at 9:54 Comment(0)
S
4

If you're already using commons-lang3 you can do this, which also checks for null and whitespace:

assertTrue(StringUtils.isNotBlank(string));

As described in their javadocs:

isNotBlank : Checks if a CharSequence is not empty (""), not null and not whitespace only.

Shrike answered 3/4, 2018 at 20:28 Comment(2)
Great solution too!!! I'll take this into consideration for next cases.Recalcitrant
As OP didn't mention the "blank" case, entpnerd's answer is more relevant.Jesu
P
3

I'd use assertThat(string, is(not(equalTo("")))). Unlike other approaches that involve checking the result of the string's .length() or .isEmpty() methods, this will show you the string's contents in the error message when the test fails.

(Edit: Actually, no, I wouldn't. I'd use the emptyString() or isEmptyString() matcher as explained in holi-java's answer. Upvote that one, not this one.)

Pantile answered 20/5, 2017 at 14:25 Comment(0)
N
3

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

assertTrue(StringUtils.isNotEmpty(str));
Nephralgia answered 8/9, 2018 at 3:54 Comment(3)
It's not a good solution for tests because you will not see the value when it fails.Thunderous
I hear what you're saying but I think that it's a decent solution for tests. I use lines of code like this in my own tests from time to time, and they work well enough.. As for the value, itself, all you're validating is that it isn't empty. Thus, if this assertion fails, the only possible values for str are null and "". In the event that you truly do want to see the value if the test fails, you can always use the slightly different version of the above line of code: assertTrue("String was empty. str=" + str, StringUtils.isNotEmpty(str));.Nephralgia
Ah, yeah, actually I found this question while looking for the opposite, isEmpty.Thunderous
M
2

Write your own TestHelper class where you can collect custom methods for assertions, e.g.

 public static void assertEmpty(String input) {...}
Margrettmarguerie answered 20/5, 2017 at 14:13 Comment(3)
This is something like which can be implemented by me. Is that mean, there's no other way using Mathcers?Recalcitrant
It's just a hint. The larger your application grows it is helpful to have custom assertions and helper methods that support testing your own business logic. For instance, instead of testing assertTrue(password.length>6) you could have a assertPasswordOk(password) method that checks all criteria for a valid password.Margrettmarguerie
That approach is fine for things that are domain specific. For such generic things like asserting emptiness, refer to libraries like AssertJ, as suggested by @Tomasz Bawor.Paleobotany
K
1

What you want to assert is the size of your string.

assertThat("String is empty",
       string.length(),
       greaterThan(0));
Karolekarolina answered 20/5, 2017 at 14:17 Comment(1)
If the String is null it would throw NullPointerException.Clash
D
1

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

Diastasis answered 8/9, 2018 at 3:16 Comment(1)
Thanks for the answer. but my question in not related to that the string can be null, but the way of asserting that string is not empty (I have covered the nullability part, it is out of the scope of this question).Recalcitrant
S
0

Without hamcrest:

    assertFalse(StringUtils.isEmpty(string));
Spyglass answered 27/11, 2019 at 11:34 Comment(0)
M
0

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");
Malversation answered 15/1, 2020 at 19:15 Comment(1)
NOT CORRECT: assertNotNull and assertNull do not verify whether the String is empty (""); they only check whether it's null.Dispart

© 2022 - 2024 — McMap. All rights reserved.