如何断言字符串不为空

How to assertThat String is not empty

在junit中断言一个string不为空可以通过以下方式完成:

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

我的问题是:有没有更好的方法来检查这个 - 比如:

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

编写您自己的 TestHelper class,您可以在其中收集断言的自定义方法,例如

 public static void assertEmpty(String input) {...}

您要断言的是字符串的大小。

assertThat("String is empty",
       string.length(),
       greaterThan(0));

您还可以使用名为 AssertJ 的库,它可以为您的代码提供非常流畅的断言。检查可以优雅地完成:

assertThat(myString).isNotEmpty();

我会使用 assertThat(string, is(not(equalTo(""))))。与涉及检查字符串的 .length().isEmpty() 方法的结果的其他方法不同,这将在测试失败时在错误消息中向您显示字符串的内容。

(编辑: 实际上,不,我不会。我会使用 emptyString()isEmptyString() 匹配器,如 。赞那个,不赞这个。)

在 hamcrest 1.3 中你可以使用 Matchers#isEmptyString :

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

在 hamcrest 2.0 中你可以使用 Matchers#emptyString :

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

更新 - 注意:"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." 来源:hamcrest.org/JavaHamcrest/distributables

您可以使用 JUnit 自己的 assertNotEquals 断言:

Assert.assertNotEquals( "", string );

如果您已经在使用 commons-lang3,您可以这样做,它还会检查 null 和空格:

assertTrue(StringUtils.isNotBlank(string));

如他们的 javadoc 中所述:

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

可以使用GoogleGuava库方法Strings.isNullOrEmpty

来自 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

考虑使用 Apache 的 StringUtils.isNotEmpty() 方法,这是对空字符串的 null 安全检查。

assertTrue(StringUtils.isNotEmpty(str));

没有腿嵴:

    assertFalse(StringUtils.isEmpty(string));

如果您使用的是 JUnit5,则可以使用 assertNotNull("yourString"); 断言您的 String 是否为空或 null 。

或者,如果您需要消息,则可以使用

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