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在正在测试的类中是空的,但我不确定我可能做错了什么,Mockito文档似乎没有帮助我。想法吗?

您的@Autowired字段的类型是AdHockReportServiceImpl;如果你想用@ injectmock来注入它,你需要把它变成AdHocReportDao,就像在测试中一样。

无论这是否是您的根本原因,这都是@InjectMocks脆弱的原因之一,您可能应该更倾向于使用显式setter或构造函数进行测试。

相关内容

  • 没有找到相关文章

最新更新