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.Environment; 9 import org.jmock.examples.calculator.Expression; 10 import org.jmock.examples.calculator.SimpleEnvironment; 11 import org.jmock.examples.calculator.expression.VariableReference; 12 13 14 public class VariableReferenceTest extends MockObjectTestCase 15 { 16 17 private final String variableName = "VARIABLE NAME"; 18 private Mock mockDefinition; 19 private VariableReference variableReference; 20 21 public void setUp() { 22 mockDefinition = mock(Expression.class, "mockDefinition"); 23 variableReference = new VariableReference(variableName); 24 } 25 26 public void testEvaluatesDefinitionOfReferencedVariable() throws Exception { 27 Mock mockEnvironment = mock(Environment.class); 28 double result = 1234; 29 30 mockEnvironment.expects(once()).method("getVariable").with(eq(variableName)) 31 .will(returnValue(mockDefinition.proxy())); 32 mockDefinition.expects(once()).method("evaluate").with(same(mockEnvironment.proxy())) 33 .will(returnValue(result)); 34 35 assertEquals("should be result of evaluating variable definition", 36 result, 37 variableReference.evaluate((Environment)mockEnvironment.proxy()), 38 0); 39 } 40 41 public void testPassesBackExceptionsFromVariableDefiniton() { 42 SimpleEnvironment environment = new SimpleEnvironment(); 43 environment.setVariable(variableName, (Expression)mockDefinition.proxy()); 44 CalculatorException thrown = new CalculatorException("THROWN EXCEPTION"); 45 46 mockDefinition.expects(once()).method("evaluate").with(eq(environment)) 47 .will(throwException(thrown)); 48 49 try { 50 variableReference.evaluate(environment); 51 fail("expected CalculatorException to be thrown"); 52 } 53 catch (CalculatorException caught) { 54 assertSame("should be thrown exception", thrown, caught); 55 } 56 } 57 58 public void testThrowsCalculatorExceptionIfVariableNotDefined() { 59 SimpleEnvironment environment = new SimpleEnvironment(); 60 61 try { 62 variableReference.evaluate(environment); 63 fail("expected CalculatorException to be thrown"); 64 } 65 catch (CalculatorException ex) { 66 assertTrue("should contain variable name in message", 67 ex.getMessage().indexOf(variableName) >= 0); 68 } 69 } 70 } 71 | Popular Tags |