Add source code for article BAEL-3379

This commit is contained in:
Yavuz Tas
2019-10-21 15:36:54 +02:00
parent f89232dd21
commit b03aa3f99f
2 changed files with 88 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
package org.baeldung.javaxval.messageinterpolator;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
public class Person {
@Size(min = 10, max = 200, message = "Name should be in-between {min} and {max} characters")
private String name;
@Min(value = 18, message = "Age should not be less than {value} but it is ${validatedValue}")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@@ -0,0 +1,58 @@
package org.baeldung.javaxval.messageinterpolator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import org.junit.BeforeClass;
import org.junit.Test;
public class ParameterMessageInterpolaterIntegrationTest {
private static Validator validator;
@BeforeClass
public static void beforeClass() {
ValidatorFactory validatorFactory = Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator())
.buildValidatorFactory();
validator = validatorFactory.getValidator();
}
@Test
public void ifNameLengthIsLess_nameValidationFails() {
Person person = new Person();
person.setName("John Doe");
person.setAge(18);
Set<ConstraintViolation<Person>> violations = validator.validate(person);
assertEquals(1, violations.size());
ConstraintViolation<Person> violation = violations.iterator().next();
assertEquals("Name should be in-between 10 and 200 characters", violation.getMessage());
}
@Test
public void ifAgeIsLess_ageMinValidationFails() {
Person person = new Person();
person.setName("John Stephaner Doe");
person.setAge(16);
Set<ConstraintViolation<Person>> violations = validator.validate(person);
assertEquals(1, violations.size());
ConstraintViolation<Person> violation = violations.iterator().next();
assertEquals("Age should not be less than 18 but it is ${validatedValue}", violation.getMessage());
}
}