'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. 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. Please suggest.

Thanks,



Solution 1:[1]

Use Integer.parseInt(string). If string contains characters other than numbers then method will throw NumberFormatException.

try{
   Integer.parseInt(inputString)
}catch(NumberFormatException exception){
   //assert fail
}

Solution 2:[2]

If you use AssertJ, you have the method "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();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sagar Gandhi
Solution 2 MauroB