Goldbones
Goldbones

Reputation: 1457

Unit test for Validation of a String in Java

I want to check if a specific String cannot have more length than 5 chars, start with letter "S" and is all in Upper Case. (this is just an example)

Imagine that you have this kind of behavior multiply by 20 fields on an object.

I want to write a unit test that says that if_all_the_fields_are_correct_validation_should_return_true();

My questions are:

I will test individually each field, but I prefer also to get an immediate result for all of my fields.

UPDATE:

My focus is not in the method of string validation. That is already made.

My question is:

Let´s make a simple example.

For instance I have an object called MyValid. Inside it I have a String, an Integer and a date.

On a class ValidationOfMyValid I have a method called isValid(String a, Integer b, Date c);

Example of asserts that needs to be done:

if_all_the_fields_on_My_Valid_is_Right(){
    assertThat(this.myValid.isValid("STACK", 12, "20081205")).isTrue();
    assertThat(this.myValid.isValid("STACK", "integer", "20081205")).isFalse();
    assertThat(this.myValid.isValid("stack", "ee", "20081205")).isFalse();    
}

As you can see, there are hundred of possibilities. What should be done in this case?

Upvotes: 0

Views: 1435

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109597

You can make a small function:

boolean stringIsValid(String s) {
    return s.matches("S[A-Z]{1,4}");
}

Then I would make several asserts so failure the wrong value and its cause can be shown.

Upvotes: 0

Yati Sawhney
Yati Sawhney

Reputation: 1402

You can use reflection for this in your testcase. That's a kind of hack:

Class aClass = MyPOJO.class  ...//obtain class object
Field[] fields = aClass.getFields();

for(Field field: fields){
    if(field.getType() instanceof String){
        // Use whatever regex you have for assertions
    }
}

Upvotes: 2

Related Questions