简体   繁体   English

具有空指针异常的PowerMock私有方法

[英]PowerMock Private method with null pointer exception

So I have code something like this 所以我有这样的代码

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) {
    ...
}

I wanted to use powerMock to return the jobs but it always return null for si. 我想使用powerMock返回作业,但它始终为si返回null。

In my test I have 在我的测试中

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

How do I write the next procedure to skip or to return a proper Job without hitting null value? 如何编写下一个跳过或返回正确的Job而不会达到null值的过程? I have also mocked si SearchIndex si = Mockito.mock(SearchIndex.class); 我还嘲笑si SearchIndex si = Mockito.mock(SearchIndex.class);

Why not wrap the SearchIndex into your own class. 为什么不将SearchIndex包装到您自己的类中。

class JobReader {

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

and then you can mock the JobReader without PowerMock. 然后您可以在没有PowerMock的情况下模拟JobReader。 Just inject it to wherever you need to use it. 只需将其注入您需要使用的任何地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM