gpt4 book ai didi

java - Mockito void doAnswer 正确用法和目的

转载 作者:行者123 更新时间:2023-11-29 08:32:52 25 4
gpt4 key购买 nike

今天我学习了 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();
}
}

由于 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 = false;
assertEquals(expected, controller.isRunning());
}

但是,我不明白这样的测试的目的是什么。我为什么要这样测试它,因为它永远不会失败(参数 isRunning 正在按我预期的方式设置)。基本上我只需要测试某些字段的状态(例如 isRunningexecutor)。但是,这些字段没有公共(public) getter 或 setter。

因此,我认为我误解了deAnswer 的用法。有人可以帮帮我吗?

最佳答案

如果我理解您的代码示例,您似乎在模拟您想要测试的对象,这在 99.9% 的情况下是不允许的。您通常只想模拟您正在测试的类的直接合作者。协作者由诸如注入(inject)服务(或其他注入(inject)字段)和您正在测试的方法的参数之类的东西组成——本质上是在您调用被测试的方法之前代表被测类的初始状态的任何东西。

关于java - Mockito void doAnswer 正确用法和目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com