-
Notifications
You must be signed in to change notification settings - Fork 233
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.Size(min = 5, max = 10)
private List<String> nickNames;
@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 nickNames
will be a list containing a random number of String
s in the [5, 10] range and the 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. 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>
Bean validation constraint parameters will take precedence over global parameters, except for custom randomizers and registries. This means that, in the previous example:
-
nickNames
will still be populated with a random number of elements in the [5, 10] range, even if thecollectionSizeRange
is set to [1, 4] for example. - if a custom
Date
randomizer generating dates in the future is registered for the fieldbirthdate
, then this field will be randomized with a date in the future and not in the past anymore as declared by the constraint.
The following example shows the expected behaviour:
@Test
void testParametersPrecedence() {
// given
class Person {
@Size(min = 5, max = 10)
private List<String> names;
@javax.validation.constraints.Past
private LocalDate birthDate;
}
LocalDate today = LocalDate.now();
EasyRandomParameters parameters = new EasyRandomParameters().collectionSizeRange(1, 4)
.randomize(FieldPredicates.named("birthDate").and(FieldPredicates.inClass(Person.class)),
new LocalDateRangeRandomizer(today, today.plusYears(10)));
EasyRandom easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person.names.size()).isBetween(5, 10); // Bean Validation constraint parameters take precedence
assertThat(person.birthDate).isAfterOrEqualTo(today); // custom randomizers take precedence
}
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
.
Easy Random is created by Mahmoud Ben Hassine with the help of some awesome contributors!