繁体   English   中英

在JUnit / Mockito测试中使用模拟对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM