[英]Use Mocked object in JUnit / Mockito test
我有一个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
问题(因此,此时简单的接口模拟就足够了)
您可以简单地使用(在setUp中)模拟它
threadPoolExtendedExecutor =模拟(ThreadPoolExtendedExecutor.class);
@Before
public void setUp() {
threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);
handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}
您还可以让MockitoJUnitRunner为您做到这一点:不要忘记通过使用@InjectMocks对其进行注释将模拟注入到您的测试服务中
@RunWith(MockitoJUnitRunner.class)
public class EventHandlerTest {
@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
如果要在测试类字段上使用@Mock
或@InjectMocks
批注,则需要在类级别添加@RunWith(MockitoJUnitRunner.class)
。
@RunWith(MockitoJUnitRunner.class)
public class EventHandlerTest {
@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
另一种方法是不使用上述注释, org.mockito.Mockito.mock()
通过调用org.mockito.Mockito.mock()
手动创建org.mockito.Mockito.mock()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.