01: package net.sf.oval.test.guard;
02:
03: import java.math.BigDecimal;
04: import java.util.Date;
05:
06: import junit.framework.TestCase;
07: import net.sf.oval.constraint.Assert;
08: import net.sf.oval.constraint.NotNull;
09: import net.sf.oval.exception.ConstraintsViolatedException;
10: import net.sf.oval.guard.Guard;
11: import net.sf.oval.guard.Guarded;
12: import net.sf.oval.guard.Post;
13: import net.sf.oval.guard.Pre;
14:
15: public class PrePostGroovyTest extends TestCase {
16: @Guarded
17: public static class TestTransaction {
18: @SuppressWarnings("unused")
19: private Date date;
20:
21: @SuppressWarnings("unused")
22: private String description;
23:
24: private BigDecimal value;
25:
26: @Pre(expr="_this.value!=null && value2add!=null && _args[0]!=null",lang="groovy",message="PRE")
27: public void increase1(
28: @Assert(expr="_value!=null",lang="groovy",message="ASSERT")
29: final BigDecimal value2add) {
30: value = value.add(value2add);
31: }
32:
33: @Post(expr="_this.value>_old.value",old="[value:_this.value]",lang="groovy",message="POST")
34: public void increase2(@NotNull
35: final BigDecimal value2add) {
36: value = value.add(value2add);
37: }
38:
39: @Post(expr="_this.value>_old.value",old="[value:_this.value]",lang="groovy",message="POST")
40: public void increase2buggy(@NotNull
41: final BigDecimal value2add) {
42: value = value.subtract(value2add);
43: }
44: }
45:
46: public void testPostGroovy() {
47: final Guard guard = new Guard();
48: TestGuardAspect.aspectOf().setGuard(guard);
49:
50: final TestTransaction t = new TestTransaction();
51:
52: try {
53: t.value = new BigDecimal(-2);
54: t.increase2buggy(new BigDecimal(1));
55: fail();
56: } catch (final ConstraintsViolatedException ex) {
57: assertEquals(ex.getConstraintViolations()[0].getMessage(),
58: "POST");
59: }
60:
61: t.increase2(new BigDecimal(1));
62: }
63:
64: public void testPreGroovy() {
65: final Guard guard = new Guard();
66: TestGuardAspect.aspectOf().setGuard(guard);
67:
68: final TestTransaction t = new TestTransaction();
69:
70: try {
71: t.increase1(new BigDecimal(1));
72: fail();
73: } catch (final ConstraintsViolatedException ex) {
74: assertEquals(ex.getConstraintViolations()[0].getMessage(),
75: "PRE");
76: }
77:
78: try {
79: t.value = new BigDecimal(2);
80: t.increase1(null);
81: fail();
82: } catch (final ConstraintsViolatedException ex) {
83: assertEquals(ex.getConstraintViolations()[0].getMessage(),
84: "ASSERT");
85: }
86: try {
87: t.increase1(new BigDecimal(1));
88: } catch (final ConstraintsViolatedException ex) {
89: System.out.println(ex.getConstraintViolations()[0]
90: .getMessage());
91: }
92: }
93: }
|