[英]Use Mocked object in JUnit / Mockito test
I have a JUnit test that reads 我有一个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);
}
}
When I call new in setUp, I have threadPoolExtendedExecutor=null
. 当我在setUp中调用new时,我有threadPoolExtendedExecutor=null
。 I would like to insert some mocked threadPoolExtendedExecutor
so, I do not have NullPointer
problems when calling its methods (so simple interface mock is enough for me at this moment) 我想插入一些模拟的threadPoolExtendedExecutor
因此,在调用其方法时我没有NullPointer
问题(因此,此时简单的接口模拟就足够了)
You can simply mock it using (in setUp) 您可以简单地使用(在setUp中)模拟它
threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class); threadPoolExtendedExecutor =模拟(ThreadPoolExtendedExecutor.class);
@Before
public void setUp() {
threadPoolExtendedExecutor = mock(ThreadPoolExtendedExecutor.class);
handler = new EventHandler(subBuffers, threadPoolExtendedExecutor);
}
You can also let MockitoJUnitRunner do it for you : don't forget to inject mocks in your service under test by annotating it with @InjectMocks 您还可以让MockitoJUnitRunner为您做到这一点:不要忘记通过使用@InjectMocks对其进行注释将模拟注入到您的测试服务中
@RunWith(MockitoJUnitRunner.class)
public class EventHandlerTest {
@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
If you would like to use the @Mock
or @InjectMocks
annotations on the test class fields then you need to add @RunWith(MockitoJUnitRunner.class)
at the class level. 如果要在测试类字段上使用@Mock
或@InjectMocks
批注,则需要在类级别添加@RunWith(MockitoJUnitRunner.class)
。
@RunWith(MockitoJUnitRunner.class)
public class EventHandlerTest {
@Mock
ThreadPoolExtendedExecutor threadPoolExtendedExecutor;
Another approach is to not use the above annotations and manually create mocks by calling org.mockito.Mockito.mock()
. 另一种方法是不使用上述注释, org.mockito.Mockito.mock()
通过调用org.mockito.Mockito.mock()
手动创建org.mockito.Mockito.mock()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.