1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.validator.xwork2.field;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.junit.After;
27 import org.junit.AfterClass;
28 import org.junit.Assert;
29 import org.junit.Before;
30 import org.junit.BeforeClass;
31 import org.nuiton.validator.NuitonValidator;
32 import org.nuiton.validator.NuitonValidatorFactory;
33 import org.nuiton.validator.NuitonValidatorResult;
34
35 import java.io.File;
36 import java.util.List;
37
38
39
40
41
42
43
44
45
46
47 public abstract class AbstractFieldValidatorTest<B> extends Assert {
48
49
50 private static final Log log =
51 LogFactory.getLog(AbstractFieldValidatorTest.class);
52
53 protected static NuitonValidator<?> cacheValidator;
54
55 protected static File basedir;
56
57 protected final Class<B> type;
58
59 protected NuitonValidator<B> validator;
60
61 protected B bean;
62
63 public AbstractFieldValidatorTest(Class<B> type) {
64 this.type = type;
65 }
66
67
68
69
70
71
72
73
74
75 public abstract void testValidator() throws Exception;
76
77 @Before
78 @SuppressWarnings("unchecked")
79 public void setUp() throws Exception {
80 log.debug("start test " + getClass().getSimpleName());
81 bean = type.newInstance();
82 if (cacheValidator == null) {
83 validator = NuitonValidatorFactory.newValidator(type);
84 cacheValidator = validator;
85 } else {
86 validator = (NuitonValidator<B>) cacheValidator;
87 }
88 }
89
90 @After
91 @SuppressWarnings("unchecked")
92 public void tearDown() {
93 }
94
95 @AfterClass
96 public static void afterclass() throws Exception {
97 cacheValidator = null;
98 }
99
100 @BeforeClass
101 public static void initValidator() throws Exception {
102
103 String b = System.getenv("basedir");
104 if (b == null) {
105 b = new File("").getAbsolutePath();
106 }
107 basedir = new File(b);
108 }
109
110 @SuppressWarnings("unchecked")
111 protected void assertFieldInError(String fieldName, String error, boolean required) {
112
113 NuitonValidatorResult result = validator.validate(bean);
114
115 List<String> errorMessages = result.getErrorMessages(fieldName);
116
117 boolean errorFound = errorMessages.contains(error);
118
119 if (required) {
120
121
122
123 assertTrue("error " + error + " should not exist but was found.", errorFound);
124 } else {
125
126
127 assertFalse("error " + error + " should exist but was not found.", errorFound);
128 }
129 }
130 }