小编Coo*_*zza的帖子

Mockito void doAnswer 正确用法和目的

今天我了解了 Mockito,在玩弄它时我发现了一些我不明白的东西。

假设我想测试以下代码:

    public void stop(boolean showMessage) {
    if(executor != null && !executor.isShutdown() && this.isRunning) {
        if(showMessage) { 
            View.getSingleton().showMessageDialog(Constant.messages.getString("sessionchecker.stopmessage"));
        }

        executor.shutdownNow();
        executor = null;
        extension.getCountdownTimer().stopCountdown();

        this.isRunning = false;
        this.usersReady.clear();
    }
}
Run Code Online (Sandbox Code Playgroud)

由于 stop 方法是无效的,我需要调用doAnswer(如果我理解正确的话)。所以我尝试了以下方法:

    @Test
public void testStopIsRunningFalse() {
    Mockito.when(controller.isRunning()).thenReturn(true); // Mock a running service
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            if(controller.isRunning()) {
                // Normally would actually shut down service
                Mockito.when(controller.isRunning()).thenReturn(false); // Service should stop
            }
            return null;
        }
    }).when(controller).stop(false);
    controller.stop(false);
    boolean expected …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mockito

1
推荐指数
1
解决办法
5098
查看次数

标签 统计

java ×1

mockito ×1

unit-testing ×1