Java JSR 303 bean validation: a simple example
March 05, 2012 20:32:37 Last update: March 05, 2012 20:32:37
In this simple example, I create a simple validating bean and create a JUnit test to test the validation.
- The bean (
src/main/java/com/example/Person.java):package com.example; import javax.validation.constraints.NotNull; public class Person { @NotNull private String name; public Person(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
- The test (
src/test/java/com/example/TestPerson.java):package com.example; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class TestPerson { private Validator validator; @Before public void setUp() { ValidatorFactory f = Validation.buildDefaultValidatorFactory(); validator = f.getValidator(); } @Test public void testNameNull() { Person p = new Person(null); Set<ConstraintViolation<Person>> violations = validator.validate(p); assertEquals(1, violations.size()); } @Test public void testNameEmpty() { Person p = new Person(" "); Set<ConstraintViolation<Person>> violations = validator.validate(p); assertEquals(1, violations.size()); } }
- Run the test:
mvn clean test
You'll notice that one test passed and the other failed. - The tests require that a person must have a name and the name cannot be empty, so
@NotNullis not the right rule to use here. To make sure that the name is not empty, we need to use@Pattern. But since a null String matches any pattern,@NotNullis also needed:package com.example; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; public class Person { @NotNull @Pattern(regexp="\\w.*") private String name; public Person(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } }