如何使用Mockito模拟带有自定义注释的类?

时间:2018-08-22 07:44:03

标签: java unit-testing annotations mockito

我正在为CatalogFacade类编写单元测试;该类是这样的:

public class CatalogFacade{
    @Inject
    @Shallow //custom annotation
    private ITServiceMapper servMapper;
    @Inject
    @Complete //custom annotation
    private ITServiceMapper dServMapper;

    @Override
    public ITService getITService(String serviceCode) {

        ITService a = dServMapper.method();
        return a;
    }

}

我以这种方式编写了单元测试:

@RunWith(MockitoJUnitRunner.class)
public class CatalogFacadeTest {

    @InjectMocks
    private CatalogFacade facade;
    @Mock
    private ITServiceMapper servMapperMock;
    @Mock
    private ITServiceMapper dServMapperMock;

    @Test
    public void getITService() {
        /* prepare value objects */
        ITService dtoMock= Mockito.mock(ITService.class);

        /* Given some preconditions (Arrange) */
        given(dServMapperMock.modelToDto(entityMock)).willReturn(dtoMock);

        /* When an action occurs (Act) */
        ITService service= facade.getITService("AMS-SA-0001");

        /* Then verify the output (Assert) */
        assertThat(dtoMock.getItServiceCode(),
        is(equalTo(service.getItServiceCode())));
    }
}

但是该测试抛出NullPointeException,因为调用dServMapperMock.method()时,dservMapperMock为null,所以我认为它没有被正确模拟...

我认为问题可能出在ITServiceMapper具有自定义注释的类上,我无法模拟它。

我该如何模拟此类?

谢谢!

1 个答案:

答案 0 :(得分:1)

此方法不起作用的主要原因是,您的类(CatalogFacade)中有多个ITServiceMapper实例。

在这些情况下,Mockito(特别是@InjectMocks)存在一些问题。解决此问题的最简单方法是通过协助Mockito使用name属性,例如

@Mock(name = "servMapper")
private ITServiceMapper servMapper;

@Mock(name = "dServMapper")
private ITServiceMapper dServMapperMock;

这是构造函数注入总是比字段注入更好的原因之一。 查看this文章以了解更多信息