Home > Net >  How to write a test in Java that would check if a String contains any alphabetic characters?
How to write a test in Java that would check if a String contains any alphabetic characters?

Time:09-12

In a piece of code (exercise for a bootcamp) I had to solve some tasks. One of those tasks is to check if a String that is provided to my method has a length of exactly x digits. This String is hypothetically a social security number, so it should contain only numeric values.
Therefore, I would like to create a test that would check that all the characters in the socialSecurityNumber String are only numeric values.

I've only seen tests that use simple checks, like assertEquals (expected: 10, Actual: etc). But how would I write in a test something like "matches("[a-zA-Z] ")"?

I'm thinking

        @Test
      void stringTextShouldGiveError (String socialSecurityNumber){
        boolean check = false;
        if (socialSecurityNumber.matches("[a-zA-Z] ")){
          check = true;
        }
        assertFalse();


How would I make the above work? Thanks

CodePudding user response:

Another option is using enter image description here

CodePudding user response:

Stream of code points

To work with individual characters, use code point integer numbers. Every character in Unicode is assigned a permanent number, its code point.

The Western Arabic numerals 0-9 have code points 48-57, inclusive. The HYPHEN-MINUS character has a code point of 45.

int[] ssnCodePoints = IntStream.concat( IntStream.of( 45 ) , IntStream.rangeClosed( 48 , 57 ) ).toArray() ;

Test if any of the input code points is not one of our desired characters. Our call to findAny returns an OptionalInt. If empty, that means no unexpected characters were found.

boolean containsOnlySsnCharacters = 
    Arrays
    .toStream( input.codePoints() )
    .filter( codePoint -> Arrays.binarySearch( ssnCodePoints , codePoint ) < 0 )  // Filter for unexpected characters. 
    .findAny()  // Stop checking after finding any unexpected character. 
    .isEmpty() 
;

This addresses the specifics of your Question. Be aware that this is not enough in real work. You would also test the length, and verify by position of each expected digit and each HYPHEN-MINUS.

  • Related