我正在尝试用Mockito编写非常简单的测试。我写了一小段代码:
public class FlowTests {
@Mock
Calculator mockCalc = Mockito.mock(Calculator.class);
ConsoleView mockView = Mockito.mock(ConsoleView.class);
@Test
public void a01_Test() {
final String s = "2+2*2";
Controller c = new Controller();
c.setCalc(mockCalc);
Mockito.when(mockView.getFormule()).thenReturn(s); // I am not sure if it works
c.setView(mockView);
c.handle();
// TODO check if evaluate method has been invoked with "2+2*2"
}
}
在这里,您可以看到与此测试关联的类:
public class Controller {
private IView view = new ConsoleView();
private ICalculator calc = new Calculator();
Double value = null;
public void handle() {
String formule = view.getFormule();
Double value = calc.evaluate(formule);
if (value != null) {
System.out.println("Result: ");
view.appendAnswer(value);
}
}
public void setCalc(ICalculator calc) {
this.calc = calc;
}
public void setView(IView view) {
this.view = view;
}
}
public class Calculator implements ICalculator {
public double evaluate(String s) {
...
char[] formuleChar = s.toCharArray();
result = calc.eval(formuleChar);
return result;
}
}
public class ConsoleView implements IView {
public String getFormule() {
... // getting s from console
return s;
}
public void appendAnswer(double r) {
System.out.println(r);
}
}
我测试的第一个目标是在 ConsoleView 中模拟函数 getFormule() 以始终返回字符串 s = "2+2*2"。我做到了,但我不确定它是否有效。
主要目标是检查计算器类中的方法 evaluate() 是否使用相同的字符串调用。我不知道该怎么做。
我无法修改我的代码。我只能写一个测试。
提前感谢您的帮助!
尝试这样的事情:
// check if evaluate method has been invoked with "2+2*2"
verify(mockCalc).evaluate("2+2*2");