[英]Assert to check string contains only numeric values
I want to write a JUNIT test case for checking that a String contains only numeric values.我想编写一个 JUNIT 测试用例来检查 String 是否只包含数值。 Can anybody suggest me to do so.任何人都可以建议我这样做。 I am new to junit test case and i cud not find any way to write an assert for it.我是 junit 测试用例的新手,我找不到任何方法为其编写断言。 Please suggest.请建议。
Thanks,谢谢,
Use Integer.parseInt(string)
. 使用Integer.parseInt(string)
。 If string contains characters other than numbers then method will throw NumberFormatException
. 如果string包含除数字以外的字符,则method将抛出NumberFormatException
。
try{
Integer.parseInt(inputString)
}catch(NumberFormatException exception){
//assert fail
}
If you use AssertJ , you have the method "containsOnlyDigits"如果你使用AssertJ ,你有方法“containsOnlyDigits”
@Test
void shouldContainOnlyDigits() {
assertThat("123").containsOnlyDigits();
}
or you can improve the check if you have a String that should contain a padded number:或者如果你有一个应该包含填充数字的字符串,你可以改进检查:
@Test
void shouldContainOnlyDigits() {
assertThat("001").hasSize(3).containsOnlyDigits();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.