1   package org.mod4j.runtime.validation;
2   
3   import static org.junit.Assert.assertEquals;
4   import static org.junit.Assert.fail;
5   
6   import java.util.Arrays;
7   
8   import org.junit.Test;
9   import org.mod4j.runtime.exception.BusinessRuleException;
10  import org.mod4j.runtime.validation.BusinessRuleValidationTemplate;
11  import org.springframework.validation.Errors;
12  import org.springframework.validation.Validator;
13  
14  public class BusinessRuleValidationTemplateTest {
15      public class TestValidator implements Validator {
16  
17          @SuppressWarnings("unchecked")
18          public boolean supports(Class clazz) {
19              return clazz.isAssignableFrom(ObjectToValidate.class);
20          }
21  
22          public void validate(Object target, Errors errors) {
23              errors.reject("this.is.an.error");
24          }
25      }
26  
27      public class ObjectToValidate {
28          private String value;
29  
30          public ObjectToValidate(String value) {
31              this.value = value;
32          }
33  
34          public String getValue() {
35              return value;
36          }
37  
38          public void setValue(String value) {
39              this.value = value;
40          }
41      }
42  
43      @Test
44      public void testInvokeValidator() {
45          ObjectToValidate target = new ObjectToValidate("value");
46          BusinessRuleValidationTemplate template = new BusinessRuleValidationTemplate(target);
47          try {
48              template.invokeValidator(new TestValidator());
49              fail("Expected BusinessRuleException");
50          } catch (BusinessRuleException e) {
51              Errors errors = (Errors) e.getCause();
52              assertEquals("this.is.an.error", errors.getGlobalError().getCode());
53          }
54      }
55  
56      @Test
57      public void testInvokeValidators() {
58          ObjectToValidate target = new ObjectToValidate("value");
59          BusinessRuleValidationTemplate template = new BusinessRuleValidationTemplate(target);
60          try {
61              template.invokeValidators(Arrays.asList(new Validator[] { new TestValidator(), new TestValidator() }));
62              fail("Expected BusinessRuleException");
63          } catch (BusinessRuleException e) {
64              Errors errors = (Errors) e.getCause();
65              assertEquals(2, errors.getErrorCount());
66              assertEquals("this.is.an.error", errors.getGlobalError().getCode());
67          }
68      }
69  }