断言字符串具有一定长度 (Java)

Assert the String has certain length (Java)

有什么方法可以在方法中断言输入字符串具有特定长度吗?

我试过断言 stringName[4]; 但似乎不起作用

如果您只想使用 Java 的 assert 关键字而不是像 JUnit 这样的任何库,那么您可以使用:

String myStr = "hello";
assert myStr.length() == 5 : "String length is incorrect";

来自官方文档:

The assertion statement has two forms. The first, simpler form is:

assert Expression1;

where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.

The second form of the assertion statement is:

assert Expression1 : Expression2 ;

where: Expression1 is a boolean expression. Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

如果您使用的是 JUnit 等测试库,则可以使用以下内容:

String myStr = "hello";
assertEquals(5, myStr.length());

更新: 正如 AxelH 在评论中正确指出的那样,编译后,您 运行 第一个解决方案为 java -ea AssertionTest。 -ea 标志启用断言。

而不是使用 assert,我建议使用 Exception 作为一个简单的演示来检查变量的状态:

String[] arr = new String[3];
if (arr.length != 4) {
    throw new IllegalStateException("Array length is not expected");
}

这将通过异常直接给出提示,你不需要在jvm选项中使用assert

Exception in thread "main" java.lang.IllegalStateException: Array length is not expected
    at basic.AssertListLength.main(AssertListLength.java:7)

如果您使用的是 hamcrest,那么您可以:

 assertThat("text", hasLength(4))

参见 http://hamcrest.org/JavaHamcrest/javadoc/2.2/ > CharSequenceLength

这样做的好处是它将有一个正确的错误消息,其中包括字符串本身。

使用AssertJ hasSize():

assertThat(stringName).hasSize(4)