Created
July 22, 2012 10:41
-
-
Save mgenov/3159213 to your computer and use it in GitHub Desktop.
CalculatorTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.clouway.calculator; | |
import org.jmock.Expectations; | |
import org.jmock.Mockery; | |
import org.testng.annotations.BeforeMethod; | |
import org.testng.annotations.Test; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class CalculatorTest extends JMockFastTest { | |
Mockery context = new Mockery(); | |
interface CalculationTextBox { | |
void displayResult(Integer number); | |
} | |
class Calculator { | |
private final CalculationTextBox calculationTextBox; | |
private List<Integer> numbers = new ArrayList<Integer>(2); | |
private String operation; | |
public Calculator(CalculationTextBox calculationTextBox) { | |
this.calculationTextBox = calculationTextBox; | |
} | |
public void onNumberPressed(Integer number) { | |
numbers.add(number); | |
} | |
public void onOperationPressed(String operation) { | |
this.operation = operation; | |
} | |
public void onCalculate() { | |
if ("+".equals(operation)) { | |
calculationTextBox.displayResult(numbers.get(0) + numbers.get(1)); | |
} else if ("-".equals(operation)) { | |
calculationTextBox.displayResult(numbers.get(0) - numbers.get(1)); | |
} else if ("/".equals(operation)) { | |
calculationTextBox.displayResult(numbers.get(0) / numbers.get(1)); | |
} | |
// we need to be prepared for the next calculation | |
operation = null; | |
numbers.clear(); | |
} | |
} | |
private Calculator calculator; | |
private CalculationTextBox calculationTextBox; | |
@BeforeMethod | |
public void initializeCalculator() { | |
calculationTextBox = context.mock(CalculationTextBox.class); | |
calculator = new Calculator(calculationTextBox); | |
} | |
@Test | |
public void addTwoNumbers() { | |
allowCalculationToReturnOnly(8); | |
interpret(5, "+", 3); | |
} | |
@Test | |
public void subtractTwoNumbers() { | |
allowCalculationToReturnOnly(12); | |
interpret(14, "-", 2); | |
} | |
@Test | |
public void consistentCalculationsAreAllowed() { | |
allowCalculationToReturnOnly(3); | |
allowCalculationToReturnOnly(4); | |
interpret(6, "/", 2); | |
interpret(3, "+", 1); | |
} | |
private void interpret(int leftNumber, String operation, int rightNumber) { | |
calculator.onNumberPressed(leftNumber); | |
calculator.onOperationPressed(operation); | |
calculator.onNumberPressed(rightNumber); | |
calculator.onCalculate(); | |
} | |
private void allowCalculationToReturnOnly(final Integer expectedValue) { | |
context.checking(new Expectations() {{ | |
oneOf(calculationTextBox).displayResult(expectedValue); | |
}}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment