1 3 package test.jmock.examples.calculator.expression; 4 5 import org.jmock.Mock; 6 import org.jmock.MockObjectTestCase; 7 import org.jmock.examples.calculator.CalculatorException; 8 import org.jmock.examples.calculator.Expression; 9 import org.jmock.examples.calculator.SimpleEnvironment; 10 import org.jmock.examples.calculator.expression.Literal; 11 12 13 public abstract class AbstractBinaryOperatorTest 14 extends MockObjectTestCase 15 { 16 SimpleEnvironment environment; 17 private Mock left; 18 private Mock right; 19 20 public void setUp() { 21 environment = new SimpleEnvironment(); 22 left = mock(Expression.class, "left"); 23 right = mock(Expression.class, "right"); 24 } 25 26 protected void runOperatorTest() throws Exception { 27 for (double i = 1; i <= 10; i = i + 1) { 28 for (double j = 1; j <= 10; j = j + 1) { 29 Expression expression = makeExpression(i, j); 30 31 assertEquals(expectedValue(i, j), 32 expression.evaluate(environment), 33 0.0); 34 } 35 } 36 } 37 38 public void testReportsErrorsInLeftSubexpression() { 39 Expression expression = makeExpression((Expression)left.proxy(), 40 (Expression)right.proxy()); 41 42 CalculatorException thrown = 43 new CalculatorException("thrown exception"); 44 45 left.expects(once()).method("evaluate").with(same(environment)) 46 .will(throwException(thrown)); 47 48 try { 49 expression.evaluate(environment); 50 fail("CalculatorException expected"); 51 } 52 catch (CalculatorException caught) { 53 assertSame("should be thrown exception", thrown, caught); 54 } 55 } 56 57 public void testReportsErrorsInRightSubexpression() { 58 Expression expression = makeExpression((Expression)left.proxy(), 59 (Expression)right.proxy()); 60 61 CalculatorException thrown = 62 new CalculatorException("thrown exception"); 63 64 left.expects(once()).method("evaluate").with(same(environment)) 65 .will(returnValue(0.0)); 66 right.expects(once()).method("evaluate").with(same(environment)) 67 .will(throwException(thrown)); 68 69 try { 70 expression.evaluate(environment); 71 fail("CalculatorException expected"); 72 } 73 catch (CalculatorException caught) { 74 assertSame("should be thrown exception", thrown, caught); 75 } 76 } 77 78 protected Expression makeExpression( double leftLiteral, double rightLiteral ) { 79 return makeExpression(new Literal(leftLiteral), new Literal(rightLiteral)); 80 } 81 82 protected abstract Expression makeExpression( Expression leftExpression, 83 Expression rightExpression ); 84 85 protected abstract double expectedValue( double leftValue, double rightValue ); 86 87 } 88 | Popular Tags |