当出现任何java.lang.NullPointerException时,Mockito



我有一个必须测试的方法:

private void processRequest() {
BulkRequest request = new BulkRequest();
request.add(new IndexRequest("posts").id("1")
.source(XContentType.JSON,"field", "foo"));
request.add(new IndexRequest("posts").id("2")
.source(XContentType.JSON,"field", "bar"));
final BulkResponse bulkResponse = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
}

这就是我在测试课上要做的:

RestHighLevelClient restHighLevelClientMock = mock(RestHighLevelClient.class);
final String errorMessage = "error message";
final Exception cause = new Exception("test exception");
final boolean isFailed = true;
final int itemID = 0;
// define the item failure
BulkItemResponse.Failure failure = mock(BulkItemResponse.Failure.class);
when(failure.getCause()).thenReturn(cause);
when(failure.getMessage()).thenReturn(errorMessage);
// define the item level response
BulkItemResponse itemResponse = mock(BulkItemResponse.class);
when(itemResponse.isFailed()).thenReturn(isFailed);
when(itemResponse.getItemId()).thenReturn(itemID);
when(itemResponse.getFailure()).thenReturn(failure);
when(itemResponse.getFailureMessage()).thenReturn("error message");
List<BulkItemResponse> itemsResponses = Collections.singletonList(itemResponse);
// define the bulk response to indicate failure
BulkResponse response = mock(BulkResponse.class);
when(response.iterator()).thenReturn(itemsResponses.iterator());
when(response.hasFailures()).thenReturn(isFailed);
// have the client return the mock response
when(restHighLevelClientMock.bulk(any(BulkRequest.class), RequestOptions.DEFAULT)).thenReturn(response);

我在以下行中得到java.lang.NullPointerException

when(restHighLevelClientMock.bulk(any(BulkRequest.class), RequestOptions.DEFAULT)).thenReturn(response);

知道为什么会发生这种事吗?感谢

我也遇到了这个问题,这导致我提出了github请求:

https://github.com/elastic/elasticsearch/issues/40534

Elasticsearch的RestHighLevelClient类将许多公共方法标记为final,使其无法进行模拟。

github页面中详细介绍了一种关于创建委托的解决方法,这种方法不太理想,但有效。

编辑:在挖掘了可能的解决方案后,我发现了这篇文章:参见https://www.baeldung.com/mockito-final.我在自己的项目中尝试过,并在junit jupiter上进行了测试。

将以下内容添加到src/test/resources文件夹:

mockito-extensions/org.mockito.plugins.MockMaker

在org.mockito.plugins.MockMaker文件中添加以下行:

mock-maker-inline

相关内容

  • 没有找到相关文章

最新更新