Reputation: 63
Is there any way to assert in a method that input String has certain length?
I tried assert stringName[4];
but seems like it doesn't work
Upvotes: 4
Views: 13548
Reputation: 3432
If you are using hamcrest, then you can do:
assertThat("text", hasLength(4))
See http://hamcrest.org/JavaHamcrest/javadoc/2.2/ > CharSequenceLength
Good thing about this is that it will have a proper error message, among others including the string itself.
Upvotes: 0
Reputation: 5091
If you just want to use the Java's assert
keyword and not any library like JUnit, then you can probably use:
String myStr = "hello";
assert myStr.length() == 5 : "String length is incorrect";
From the official docs:
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 anAssertionError
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.)
You can use the following if you're using a testing library like JUnit:
String myStr = "hello";
assertEquals(5, myStr.length());
Update:
As correctly pointed out in the comments by AxelH, after compilation, you run the first solution as java -ea AssertionTest
. The -ea flag enables assertions.
Upvotes: 7
Reputation: 7828
Instead of using assert
, I'd recommend using Exception
to check the state of the variables as a simple demo:
String[] arr = new String[3];
if (arr.length != 4) {
throw new IllegalStateException("Array length is not expected");
}
This will directly give the hint by exceptions and you don't need to bother with assert
in jvm options.
Exception in thread "main" java.lang.IllegalStateException: Array length is not expected
at basic.AssertListLength.main(AssertListLength.java:7)
Upvotes: 0