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

时间:2018-12-14 09:44:29

标签: java junit junit5

我有一个读取的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中打电话给我时,我有threadPoolExtendedExecutor=null。 我想插入一些模拟的threadPoolExtendedExecutor,因此,在调用其方法时没有NullPointer问题(因此,现在简单的接口模拟就足够了)

2 个答案:

答案 0 :(得分:2)

您可以简单地使用(在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;

答案 1 :(得分:1)

如果您想在测试课程字段中使用@Mock@InjectMocks批注,则需要在课程级别添加@RunWith(MockitoJUnitRunner.class)

@RunWith(MockitoJUnitRunner.class)
public class  EventHandlerTest  {

    @Mock
    ThreadPoolExtendedExecutor threadPoolExtendedExecutor;

另一种方法是不使用上述注释,而是通过调用org.mockito.Mockito.mock()手动创建模拟。