001: package net.sf.oval.test.guard;
002:
003: import java.math.BigDecimal;
004: import java.util.Date;
005:
006: import junit.framework.TestCase;
007: import net.sf.oval.constraint.Assert;
008: import net.sf.oval.constraint.NotNull;
009: import net.sf.oval.exception.ConstraintsViolatedException;
010: import net.sf.oval.guard.Guard;
011: import net.sf.oval.guard.Guarded;
012: import net.sf.oval.guard.Post;
013: import net.sf.oval.guard.Pre;
014:
015: public class PrePostOGNLTest extends TestCase {
016: @Guarded
017: public static class TestTransaction {
018: @SuppressWarnings("unused")
019: private Date date;
020:
021: @SuppressWarnings("unused")
022: private String description;
023:
024: private BigDecimal value;
025:
026: @Pre(expr="_this.value!=null && value2add!=null && _args[0]!=null",lang="ognl",message="PRE")
027: public void increase1(
028: @Assert(expr="_value!=null",lang="ognl",message="ASSERT")
029: BigDecimal value2add) {
030: value = value.add(value2add);
031: }
032:
033: @Post(expr="_this.value>_old.value",old="#{\"value\":_this.value}",lang="ognl",message="POST")
034: public void increase2(@NotNull
035: BigDecimal value2add) {
036: value = value.add(value2add);
037: }
038:
039: @Post(expr="_this.value>_old.value",old="#{\"value\":_this.value}",lang="ognl",message="POST")
040: public void increase2buggy(@NotNull
041: BigDecimal value2add) {
042: value = value.subtract(value2add);
043: }
044:
045: /**
046: * @return the value
047: */
048: public BigDecimal getValue() {
049: return value;
050: }
051: }
052:
053: public void testPreOGNL() {
054: final Guard guard = new Guard();
055: TestGuardAspect.aspectOf().setGuard(guard);
056:
057: TestTransaction t = new TestTransaction();
058:
059: try {
060: t.increase1(new BigDecimal(1));
061: fail();
062: } catch (ConstraintsViolatedException ex) {
063: assertEquals(ex.getConstraintViolations()[0].getMessage(),
064: "PRE");
065: }
066:
067: try {
068: t.value = new BigDecimal(2);
069: t.increase1(null);
070: fail();
071: } catch (ConstraintsViolatedException ex) {
072: assertEquals(ex.getConstraintViolations()[0].getMessage(),
073: "ASSERT");
074: }
075: try {
076: t.increase1(new BigDecimal(1));
077: } catch (ConstraintsViolatedException ex) {
078: System.out.println(ex.getConstraintViolations()[0]
079: .getMessage());
080: }
081: }
082:
083: public void testPostOGNL() {
084: final Guard guard = new Guard();
085: TestGuardAspect.aspectOf().setGuard(guard);
086:
087: TestTransaction t = new TestTransaction();
088:
089: try {
090: t.value = new BigDecimal(-2);
091: t.increase2buggy(new BigDecimal(1));
092: fail();
093: } catch (ConstraintsViolatedException ex) {
094: assertEquals(ex.getConstraintViolations()[0].getMessage(),
095: "POST");
096: }
097:
098: t.increase2(new BigDecimal(1));
099: }
100: }
|