Mockito - 空指针异常

时间:2015-07-17 22:14:56

标签: unit-testing null mockito

我有一个非常简单的类(现在)只需要一个Id并将其传递给DAO。

@Service
public class AdHocReportServiceImpl {

    @Autowired
    private AdHocReportServiceImpl adHocReportDao;

    public List<AdHocReportResponseDto> getAdHocReportResults(String reportId) {
        return adHocReportDao.getAdHocReportResults(reportId);
    }
}

我正在尝试使用Mockito来验证逻辑是否存在(此应用程序没有代码覆盖率,而我正试图稍微改变一下)

@RunWith(MockitoJUnitRunner.class)
public class AdHocReportServiceTest {

@InjectMocks
private AdHocReportServiceImpl adHocReportServiceImpl = new AdHocReportServiceImpl();

@Mock
private AdHocReportDao adHocReportDao;

@Test
public void getAdHocReportResultsTest() {
    List<AdHocReportResponseDto> adHocReportResponseDtoList = new ArrayList<AdHocReportResponseDto>();
    AdHocReportResponseDto adHocReportResponseDto1 = new AdHocReportResponseDto();
    AdHocReportResponseDto adHocReportResponseDto2 = new AdHocReportResponseDto();

    adHocReportResponseDtoList.add(adHocReportResponseDto1);
    adHocReportResponseDtoList.add(adHocReportResponseDto2);

    when(adHocReportDao.getAdHocReportResults(anyString())).thenReturn(adHocReportResponseDtoList);
    adHocReportServiceImpl.getAdHocReportResults("anyString()");
}
}

Mockito说我在adHocReportDao上得到了一个空指针异常。当我进行调试时确定DAO在正在测试的类中是null但我不确定我可能做错了什么并且Mockito文档似乎没有帮助我。想法?

1 个答案:

答案 0 :(得分:0)

您的@Autowired字段的类型为AdHockReportServiceImpl;如果你想用@InjectMocks注入它,你需要像测试一样把它变成AdHocReportDao。

这是否是您的根本原因,这是@InjectMocks易碎的原因之一,您可能更喜欢使用显式设置器或构造函数进行测试。