Romi
Romi

Reputation: 4921

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,

Upvotes: 3

Views: 3528

Answers (2)

MauroB
MauroB

Reputation: 580

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();
}

Upvotes: 2

Sagar Gandhi
Sagar Gandhi

Reputation: 965

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
}

Upvotes: 1

Related Questions