1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.validator;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import org.seasar.cubby.action.Action;
22  import org.seasar.cubby.action.ActionErrors;
23  import org.seasar.cubby.validator.impl.ValidationProcessorImpl;
24  import org.seasar.extension.unit.S2TestCase;
25  
26  public class UserValidationRuleTest extends S2TestCase {
27  
28  	public ValidationProcessorImpl validationProcessor;
29  
30  	public MockAction action;
31  
32  	@Override
33  	protected void setUp() throws Exception {
34  		include(this.getClass().getName().replaceAll("\\.", "/") + ".dicon");
35  	}
36  
37  	public void testUserValidation() throws ValidationException {
38  		ActionErrors errors = action.getErrors();
39  		Object form = action;
40  		ValidationRules rules = action.rules;
41  		Map<String, Object[]> params = new HashMap<String, Object[]>();
42  
43  		validationProcessor.validate(rules, params, form, errors);
44  
45  		action.value2 = "ng";
46  		try {
47  			validationProcessor.validate(rules, params, form, errors);
48  			fail();
49  		} catch (ValidationException e) {
50  			assertEquals(1, errors.getAll().size());
51  			assertEquals("validation failed", errors.getAll().get(0));
52  		}
53  	}
54  
55  	public static class MockAction extends Action {
56  
57  		public String value1;
58  
59  		public String value2;
60  
61  		public ValidationRules rules = new DefaultValidationRules() {
62  			@Override
63  			public void initialize() {
64  				add(DATA_CONSTRAINT, new UserValidationRule());
65  			}
66  		};
67  
68  		class UserValidationRule implements ValidationRule {
69  
70  			public void apply(Map<String, Object[]> params, Object form,
71  					ActionErrors errors) {
72  				if ("ng".equals(value1) || "ng".equals(value2)) {
73  					errors.add("validation failed", "value1", "value2");
74  				}
75  			}
76  
77  		}
78  	}
79  }