首页 > 解决方案 > 在 JUnit / Mockito 测试中使用 Mocked 对象

问题描述

我有一个 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问题(此时简单的接口模拟对我来说已经足够了)

标签: javajunitjunit5

解决方案


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

threadPoolExtendedExecutor = mock(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;

推荐阅读