【问题标题】:Mockito - Null Pointer ExceptionMockito - 空指针异常
【发布时间】:2015-10-07 17:55:19
【问题描述】:

我有一个非常简单的类(现在),它只需要一个 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 文档似乎没有帮助我。想法?

【问题讨论】:

  • 我可能是个白痴。我想你已经一针见血了
  • 将评论迁移到答案。干杯!

标签: unit-testing null mockito


【解决方案1】:

您的@Autowired 字段属于 AdHockReportServiceImpl 类型;如果您希望使用 @InjectMocks 将其注入,您需要在测试中将其设为 AdHocReportDao。

无论这是否是您的根本原因,这是@InjectMocks 脆弱的原因之一,您可能应该更喜欢显式设置器或构造器进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 2019-05-24
    • 2021-06-15
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多