01: /*******************************************************************************
02: * Portions created by Sebastian Thomschke are copyright (c) 2005-2007 Sebastian
03: * Thomschke.
04: *
05: * All Rights Reserved. This program and the accompanying materials
06: * are made available under the terms of the Eclipse Public License v1.0
07: * which accompanies this distribution, and is available at
08: * http://www.eclipse.org/legal/epl-v10.html
09: *
10: * Contributors:
11: * Sebastian Thomschke - initial implementation.
12: *******************************************************************************/package net.sf.oval.test.validator;
13:
14: import java.lang.reflect.Field;
15: import java.lang.reflect.Method;
16: import java.util.List;
17:
18: import junit.framework.TestCase;
19: import net.sf.oval.ConstraintViolation;
20: import net.sf.oval.Validator;
21: import net.sf.oval.constraint.NotNullCheck;
22: import net.sf.oval.exception.InvalidConfigurationException;
23:
24: /**
25: * @author Sebastian Thomschke
26: */
27: public class AddingChecksTest extends TestCase {
28: protected static class TestEntity {
29: protected String name;
30:
31: private TestEntity(String name) {
32: this .name = name;
33: }
34:
35: /**
36: * @param name the name to set
37: */
38: public void setName(String name) {
39: this .name = name;
40: }
41: }
42:
43: /**
44: * programmatically add a NotNull constraint to the name field
45: */
46: public void testAddConstraintToField() throws Exception {
47: final Validator validator = new Validator();
48:
49: TestEntity entity = new TestEntity(null);
50: assertTrue(validator.validate(entity).size() == 0);
51:
52: Field field = TestEntity.class.getDeclaredField("name");
53: NotNullCheck notNullCheck = new NotNullCheck();
54: notNullCheck.setMessage("NOT_NULL");
55:
56: validator.addChecks(field, notNullCheck);
57:
58: List<ConstraintViolation> violations = validator
59: .validate(entity);
60: assertTrue(violations.size() == 1);
61: assertTrue(violations.get(0).getMessage().equals("NOT_NULL"));
62: }
63:
64: /**
65: * try to programmatically add a NotNull constraint to the void setter
66: * this should fail since the method is not a getter
67: */
68: public void testAddConstraintToGetter() throws Exception {
69: final Validator validator = new Validator();
70:
71: try {
72: Method setter = TestEntity.class.getDeclaredMethod(
73: "setName", new Class<?>[] { String.class });
74:
75: validator.addChecks(setter, new NotNullCheck());
76: fail();
77: } catch (InvalidConfigurationException e) {
78: //expected
79: }
80: }
81: }
|