用Mockito检查单元测试中传递的参数

时间:2013-12-27 08:59:29

标签: java testing junit mockito

我正在尝试用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()以返回String s =“2 + 2 * 2”。我做到了,但我不确定它是否有效。

主要目标是检查Calculator类中的方法evaluate()是否已使用相同的String调用。我不知道该怎么做。

我无法修改我的代码。我只能写一个测试。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

尝试这样的事情:

// check if evaluate method has been invoked with "2+2*2"
verify(mockCalc).evaluate("2+2*2");