KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > validator > ValidatorTest


1 /*
2  * $Id: ValidatorTest.java 155434 2005-02-26 13:16:41Z dirkv $
3  * $Rev$
4  * $Date: 2005-02-26 05:16:41 -0800 (Sat, 26 Feb 2005) $
5  *
6  * ====================================================================
7  * Copyright 2000-2005 The Apache Software Foundation
8  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */

21
22 package org.apache.commons.validator;
23
24 import java.text.DateFormat JavaDoc;
25 import java.text.ParseException JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Date JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Locale JavaDoc;
30
31 import junit.framework.Test;
32 import junit.framework.TestCase;
33 import junit.framework.TestSuite;
34
35 import org.apache.commons.validator.util.ValidatorUtils;
36                                                           
37 /**
38  * Performs Validation Test.
39  */

40 public class ValidatorTest extends TestCase {
41                                                           
42    public ValidatorTest(String JavaDoc name) {
43        super(name);
44    }
45
46    /**
47     * Start the tests.
48     *
49     * @param theArgs the arguments. Not used
50     */

51    public static void main(String JavaDoc[] theArgs) {
52        junit.awtui.TestRunner.main(new String JavaDoc[] {ValidatorTest.class.getName()});
53    }
54
55    /**
56     * @return a test suite (<code>TestSuite</code>) that includes all methods
57     * starting with "test"
58     */

59    public static Test suite() {
60        // All methods starting with "test" will be executed in the test suite.
61
return new TestSuite(ValidatorTest.class);
62    }
63
64    protected void setUp() {
65    }
66
67    protected void tearDown() {
68    }
69
70    /**
71     * Verify that one value generates an error and the other passes. The validation
72     * method being tested returns an object (<code>null</code> will be considered an error).
73     */

74    public void testManualObject() {
75         // property name of the method we are validating
76
String JavaDoc property = "date";
77         // name of ValidatorAction
78
String JavaDoc action = "date";
79         ValidatorResources resources = setupDateResources(property, action);
80
81       TestBean bean = new TestBean();
82       bean.setDate("2/3/1999");
83       
84       Validator validator = new Validator(resources, "testForm");
85       validator.setParameter(Validator.BEAN_PARAM, bean);
86
87       try {
88          ValidatorResults results = validator.validate();
89          
90          assertNotNull("Results are null.", results);
91          
92          ValidatorResult result = results.getValidatorResult(property);
93          
94          assertNotNull("Results are null.", results);
95          
96          assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action));
97          
98          assertTrue("Validation of the date formatting has failed.", result.isValid(action));
99       } catch (Exception JavaDoc e) {
100          fail("An exception was thrown while calling Validator.validate()");
101       }
102
103       bean.setDate("2/30/1999");
104       
105       try {
106          ValidatorResults results = validator.validate();
107          
108          assertNotNull("Results are null.", results);
109          
110          ValidatorResult result = results.getValidatorResult(property);
111          
112          assertNotNull("Results are null.", results);
113          
114          assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action));
115          
116          assertTrue("Validation of the date formatting has passed when it should have failed.", !result.isValid(action));
117       } catch (Exception JavaDoc e) {
118          fail("An exception was thrown while calling Validator.validate()");
119       }
120
121    }
122    
123    public void testOnlyReturnErrors() throws ValidatorException {
124         // property name of the method we are validating
125
String JavaDoc property = "date";
126         // name of ValidatorAction
127
String JavaDoc action = "date";
128         ValidatorResources resources = setupDateResources(property, action);
129     
130         TestBean bean = new TestBean();
131         bean.setDate("2/3/1999");
132     
133         Validator validator = new Validator(resources, "testForm");
134         validator.setParameter(Validator.BEAN_PARAM, bean);
135     
136         ValidatorResults results = validator.validate();
137     
138         assertNotNull(results);
139     
140         // Field passed and should be in results
141
assertTrue(results.getPropertyNames().contains(property));
142         
143         // Field passed but should not be in results
144
validator.setOnlyReturnErrors(true);
145         results = validator.validate();
146         assertFalse(results.getPropertyNames().contains(property));
147    }
148    
149     private ValidatorResources setupDateResources(String JavaDoc property, String JavaDoc action) {
150     
151         ValidatorResources resources = new ValidatorResources();
152     
153         ValidatorAction va = new ValidatorAction();
154         va.setName(action);
155         va.setClassname("org.apache.commons.validator.ValidatorTest");
156         va.setMethod("formatDate");
157         va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");
158     
159         FormSet fs = new FormSet();
160         Form form = new Form();
161         form.setName("testForm");
162         Field field = new Field();
163         field.setProperty(property);
164         field.setDepends(action);
165         form.addField(field);
166         fs.addForm(form);
167     
168         resources.addValidatorAction(va);
169         resources.addFormSet(fs);
170         resources.process();
171     
172         return resources;
173     }
174                                                           
175    /**
176     * Verify that one value generates an error and the other passes. The validation
177     * method being tested returns a <code>boolean</code> value.
178     */

179    public void testManualBoolean() {
180       ValidatorResources resources = new ValidatorResources();
181
182       ValidatorAction va = new ValidatorAction();
183       va.setName("capLetter");
184       va.setClassname("org.apache.commons.validator.ValidatorTest");
185       va.setMethod("isCapLetter");
186       va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List");
187       
188       FormSet fs = new FormSet();
189       Form form = new Form();
190       form.setName("testForm");
191       Field field = new Field();
192       field.setProperty("letter");
193       field.setDepends("capLetter");
194       form.addField(field);
195       fs.addForm(form);
196       
197       resources.addValidatorAction(va);
198       resources.addFormSet(fs);
199       resources.process();
200
201       List JavaDoc l = new ArrayList JavaDoc();
202
203       TestBean bean = new TestBean();
204       bean.setLetter("A");
205       
206       Validator validator = new Validator(resources, "testForm");
207       validator.setParameter(Validator.BEAN_PARAM, bean);
208       validator.setParameter("java.util.List", l);
209
210       try {
211          validator.validate();
212       } catch (Exception JavaDoc e) {
213          fail("An exception was thrown while calling Validator.validate()");
214       }
215
216       assertEquals("Validation of the letter 'A'.", 0, l.size());
217
218       l.clear();
219       bean.setLetter("AA");
220
221       try {
222          validator.validate();
223       } catch (Exception JavaDoc e) {
224          fail("An exception was thrown while calling Validator.validate()");
225       }
226       
227       assertEquals("Validation of the letter 'AA'.", 1, l.size());
228    }
229
230    /**
231     * Checks if the field is one upper case letter between 'A' and 'Z'.
232     */

233    public static boolean isCapLetter(Object JavaDoc bean, Field field, List JavaDoc l) {
234       String JavaDoc value = ValidatorUtils.getValueAsString(bean, field.getProperty());
235
236       if (value != null && value.length() == 1) {
237          if (value.charAt(0) >= 'A' && value.charAt(0) <= 'Z') {
238             return true;
239          } else {
240             l.add("Error");
241             return false;
242          }
243       } else {
244          l.add("Error");
245          return false;
246       }
247    }
248
249    /**
250     * Formats a <code>String</code> to a <code>Date</code>.
251     * The <code>Validator</code> will interpret a <code>null</code>
252     * as validation having failed.
253     */

254    public static Date JavaDoc formatDate(Object JavaDoc bean, Field field) {
255       String JavaDoc value = ValidatorUtils.getValueAsString(bean, field.getProperty());
256       Date JavaDoc date = null;
257       
258       try {
259          DateFormat JavaDoc formatter = null;
260          formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
261             
262          formatter.setLenient(false);
263              
264          date = formatter.parse(value);
265       } catch (ParseException JavaDoc e) {
266          System.out.println("ValidatorTest.formatDate() - " + e.getMessage());
267       }
268    
269       return date;
270    }
271        
272    public class TestBean {
273       private String JavaDoc letter = null;
274       private String JavaDoc date = null;
275       
276       public String JavaDoc getLetter() {
277          return letter;
278       }
279       
280       public void setLetter(String JavaDoc letter) {
281          this.letter = letter;
282       }
283
284       public String JavaDoc getDate() {
285          return date;
286       }
287       
288       public void setDate(String JavaDoc date) {
289          this.date = date;
290       }
291    }
292
293 }
Popular Tags