Java JSR 303 bean validation: a simple example 

Joined:
08/13/2009
Posts:
164

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.
  1. 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;
        }
    }
    

  2. 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());
        }
    }
    

  3. Run the test:
    mvn clean test
    

    You'll notice that one test passed and the other failed.
  4. The tests require that a person must have a name and the name cannot be empty, so @NotNull is 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, @NotNull is 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;
        }
    }
    

Share |
| Comment  | Tags