1 3 package test.jmock.examples.calculator; 4 5 import org.jmock.Mock; 6 import org.jmock.MockObjectTestCase; 7 import org.jmock.examples.calculator.*; 8 9 10 public class CalculatorTest 11 extends MockObjectTestCase 12 { 13 private Mock mockExpression; 14 private Mock mockParser; 15 private Mock mockEnvironment; 16 private Calculator calculator; 17 private final String expressionString = "<EXPRESSION>"; 18 private final String variableName = "<VARIABLE NAME>"; 19 private final String variableValueString = "<VARIABLE VALUE>"; 20 private Mock mockVariableExpression; 21 22 public void setUp() { 23 mockExpression = mock(Expression.class); 24 mockParser = mock(Parser.class); 25 mockEnvironment = mock(Environment.class); 26 mockVariableExpression = mock(Expression.class, "mockVariableExpression"); 27 28 calculator = new Calculator((Parser)mockParser.proxy(), 29 (Environment)mockEnvironment.proxy()); 30 } 31 32 public void testParsesAndCalculatesExpression() throws Exception { 33 final double expressionValue = 1.0; 34 35 mockParser.expects(once()).method("parse").with(eq(expressionString)) 36 .will(returnValue(mockExpression.proxy())); 37 mockExpression.expects(once()).method("evaluate").with(same(mockEnvironment.proxy())) 38 .will(returnValue(expressionValue)); 39 40 assertEquals("should be expression value", 41 expressionValue, calculator.calculate(expressionString), 0.0); 42 } 43 44 public void testReportsParseErrors() throws Exception { 45 final Throwable throwable = new ParseException("dummy ParseException"); 46 47 mockParser.expects(once()).method("parse").with(eq(expressionString)) 48 .will(throwException(throwable)); 49 50 try { 51 calculator.calculate(expressionString); 52 fail("ParseException expected"); 53 } 54 catch (ParseException ex) { 55 } 57 } 58 59 public void testReportsEvaluationErrors() throws Exception { 60 final Throwable throwable = new CalculatorException("dummy CalculatorException"); 61 62 mockParser.expects(once()).method("parse").with(eq(expressionString)) 63 .will(returnValue(mockExpression.proxy())); 64 mockExpression.expects(once()).method("evaluate").with(same(mockEnvironment.proxy())) 65 .will(throwException(throwable)); 66 67 try { 68 calculator.calculate(expressionString); 69 fail("CalculatorException expected"); 70 } 71 catch (CalculatorException ex) { 72 } 74 } 75 76 public void testSetsVariableExpression() throws Throwable { 77 mockParser.expects(once()).method("parse").with(eq(variableValueString)) 78 .will(returnValue(mockVariableExpression.proxy())); 79 80 mockEnvironment.expects(once()).method("setVariable") 81 .with(eq(variableName), same(mockVariableExpression.proxy())); 82 83 calculator.setVariable(variableName, variableValueString); 84 } 85 } 86 87 | Popular Tags |