View Javadoc
1   package ejava.jpa.example.validation;
2   
3   import static org.junit.Assert.*;
4   
5   import java.util.Set;
6   
7   import javax.validation.ConstraintViolation;
8   import javax.validation.Validation;
9   import javax.validation.Validator;
10  import javax.validation.ValidatorFactory;
11  
12  import org.slf4j.Logger;
13  import org.slf4j.LoggerFactory;
14  import org.junit.Test;
15  
16  /**
17   * This test case demonstrates the use of deployment descriptors to define
18   * validation for beans.
19   */
20  public class XMLTest {
21  	private static final Logger logger = LoggerFactory.getLogger(XMLTest.class);
22  	
23  	ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
24  	Validator val = vf.getValidator();
25  
26  	/**
27  	 * This test verifies the XML-based definitions will be used to 
28  	 * detect a validation error with the bean.
29  	 */
30  	@Test
31  	public void testValidationDescriptorBad() {
32  		logger.info("*** testValidationDescriptorBad");
33  		
34  		Book b = new Book();
35  		Set<ConstraintViolation<Book>> violations = val.validate(b);
36  		for (ConstraintViolation<Book> v : violations) {
37              logger.debug("{}:{} {}", v.getPropertyPath(), v.getInvalidValue(), v.getMessage());
38  		}
39  		assertEquals("unexpected number of violations", 2, violations.size());
40  	}
41  
42  	/**
43  	 * This test verifies the XML-based definitions will successfully validate
44  	 * and pass a valid bean. 
45  	 */
46  	@Test
47  	public void testValidationDescriptorGood() {
48  		logger.info("*** testValidationDescriptorGood");
49  		
50  		Book b = new Book().setTitle("Validation Rocks!").setPages(30);
51  		Set<ConstraintViolation<Book>> violations = val.validate(b);
52  		assertEquals("unexpected number of violations", 0, violations.size());
53  	}
54  }