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.
|
|
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.
|
|
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.