Skip to content

bean validation support

Mahmoud Ben Hassine edited this page Oct 31, 2020 · 12 revisions

Bean Validation support

Easy Random can introspect fields annotated with Bean Validation API annotations and generate random values according to declared validation constraints. Let's see an example, here is a Person class:

public class Person {

    private String name;

    @javax.validation.constraints.Past
    private Date birthDate;

    // constructors, getters and setters omitted
}

If you populate a Person bean using Easy Random, the generated value for birthDate field will be a random date in the past. This feature allows you to generate valid random data according to constraints already defined on your beans.

Heads up: Bean validation constraints will take precedence over custom randomizers (this means in the previous example, birthDate will still be randomized with a date in the past even if a custom Date randomizer that generates dates in the future is registered).

In order to activate Bean Validation support, you need to add the easy-random-bean-validation dependency to your project:

<dependency>
   <groupId>org.jeasy</groupId>
   <artifactId>easy-random-bean-validation</artifactId>
   <version>${latest.version}</version>
</dependency>

Note: Currently, Easy Random can generate random valid data for all Bean Validation API annotations except @Digits. There is no plan to support this annotation in a future release, you should use a custom randomizer for fields annotated with @Digits.