Contents

Test validation annotations in unit tests

Written by: David Vlijmincx

Introduction

In this post I show you how you can test the validation annotations inside unit tests. This is useful to test if the annotations are working as intended. Inside the unit test you could verify if the regex you placed inside the annotation works. Or maybe you want to verify the length of a field.

Testing validation annotations

For the example code I am going to validate the annotations on the following record. The example uses the annotations on a record, but it will also work for classes and other types.

1
2
3
4
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

record User (@NotNull @Size(min=2, max= 5)String username){ }

In the following example I show how you can validate the annotations inside a unit test. on line 12 the validator is created that is going to be used for the unit tests. The example code shows how you can use the validator to validate that the username is correct according to the annotation on the username of the User record.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.junit.jupiter.api.Test;

import java.util.Set;

import static org.junit.jupiter.api.Assertions.*;

class UserTest {
    // create a validator for the unit tests
    private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @Test
    void TestAnnotationsUsernameIsCorrect(){
        User user = new User("name");
        
        // use the validator to verify that the user instance is correct
        Set<ConstraintViolation<User>> violations = validator.validate(user);

        // with the return value you can verify if the username was the correct length
        assertTrue(violations.isEmpty());
    }

    @Test
    void TestAnnotationsUsernameIsTooLong(){
        User user = new User("NameTooLong");

        Set<ConstraintViolation<User>> violations = validator.validate(user);

        assertFalse(violations.isEmpty());
    }
}

If there are no violations that means that the object instance is correct. If violations are found the set containing the violations won't be empty. The set of violations in the last example is not empty because the username is too long, which means that there is 1 violation in the set.

Conclusion

In this post I showed you how to test the validation annotations on fields. Using the validator you can verify if the annotations are working as intended. The example unit tests are using JUnit but this works with any testing framework.