【问题标题】:PowerMock Private method with null pointer exception具有空指针异常的 PowerMock 私有方法
【发布时间】:2015-08-05 19:14:30
【问题描述】:

所以我有类似这样的代码

Class JobSearchService() {
    private SearchSetUpImpl searchSetUp;
    ...

    SearchIndex si = generateIndexes(id);
    Job jobs = si.readJobs(keyWord); // <-- si is null , null pointer         exception....
    ...
}

private Job generateIndexes(Id id) {
    ...
}

我想使用 powerMock 来返回作业,但它总是为 si 返回 null。

在我的测试中我有

PowerMockito.when(JSS, PowerMockito.method(JobSearchService.class,
    "generateIndexes", WorkId.class))
    .withArguments(id)
    .thenReturn(si);

如何编写下一个过程以跳过或返回正确的作业而不达到空值? 我也嘲笑过 si SearchIndex si = Mockito.mock(SearchIndex.class);

【问题讨论】:

    标签: java unit-testing mocking


    【解决方案1】:

    为什么不将 SearchIndex 包装到您自己的类中。

    class JobReader {
    
        Job readJobs(Id id, String keyWord) {
            SearchIndex si = generateIndexes(id);
            return si.readJobs(keyWord);
        }
    }
    

    然后您可以在没有 PowerMock 的情况下模拟 JobReader。只需将其注入您需要使用的任何地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 2020-09-11
      • 1970-01-01
      相关资源
      最近更新 更多