gpt4 book ai didi

java - 在 JUnit/Mockito 测试中使用 Mocked 对象

转载 作者:行者123 更新时间:2023-12-01 19:44:51 27 4
gpt4 key购买 nike

我有一个 JUnit 测试,内容为

public class  EventHandlerTest  {

@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;

private EventHandler handler;
private Map<Queue<SenderTask>> subBuffers = new HashMap<>();


@Before
public void setUp() {
// PROBLEM: threadPoolExtendedExecutor null!
handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}


}

当我在setUp中调用new时,我有threadPoolExtendedExecutor=null。我想插入一些模拟的threadPoolExtendedExecutor,这样,我在调用它的方法时就不会遇到NullPointer问题(所以简单的接口(interface)模拟对我来说现在就足够了)

最佳答案

您可以简单地使用(在setUp中)来模拟它

threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);

@Before
public void setUp() {
threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);
handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}

您也可以让 MockitoJUnitRunner 为您做这件事:不要忘记通过使用 @InjectMocks 注释来在测试的服务中注入(inject)模拟

@RunWith(MockitoJUnitRunner.class)
public class EventHandlerTest {

@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;

关于java - 在 JUnit/Mockito 测试中使用 Mocked 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53777120/

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