【发布时间】:2020-09-04 15:07:55
【问题描述】:
我的代码中有以下方法
public <T> T doHttpPost(String url, String data, BiFunction<String, Integer, T> responseHandler, Consumer<Exception> exceptionHandler) {
...
}
上面的方法使用如下
return APIClient.doHttpPost(url, EmptyString, null, null);
即使尝试将方法而不是空值传递给上面的 2 个参数,我仍然收到错误
在编写我的单元测试方法时,我使用的是如下设置的模拟,
doAnswer(ans -> true).when(apiClient).doHttpPost(anyString(), anyString(), any(BiFunction.class), any(Consumer.class));
doAnswer(ans -> true).when(apiClient).doHttpPost(anyString(), any(HttpEntity.class), any(BiFunction.class), any(Consumer.class));
但是,空指针异常仍然发生,因此我尝试在模拟设置中将上面的内容更改如下,仍然得到空指针异常
when(apiClient.doHttpPost(anyString(), anyString(), any(BiFunction.class), any(Consumer.class))).thenReturn(true);
when(apiClient.doHttpPost(anyString(), any(HttpEntity.class), any(BiFunction.class), any(Consumer.class))).thenReturn(true);
其他常规方法的模拟设置工作正常,它们没有通用实现。
当我在 IntelliJ IDE 的监视窗口中检查方法调用时,我发现该方法返回 null 而不是在 mock 中配置的 true。如果有办法找出mock中这两种方法设置不正确的原因,修复起来很容易
编辑 根据@Marco 的建议,我尝试了以下方法
doAnswer(ans -> true).when(apiClient).doHttpPost(anyString(), anyString(), any(), any());
当使用下面的调用方法时,
return jenkinsAPIClient.doHttpPost(url, EmptyString, null, null);
测试失败并出现以下错误
Argument(s) are different! Wanted:
APIClient#0 bean.doHttpPost(
<any string>,
<any string>,
<any java.util.function.BiFunction>,
<any java.util.function.Consumer>
);
testcasename(ServiceTests.java:435)
Actual invocations have different arguments:
APIClient#0 bean.doHttpPost(
"nulljob/CL217R/job/One/doRename?newName=aYbf8y8FRirlgXQoz7ySNhQqNp870xY0tZ9O6sSSBlbfgktoM7zb3UNdMNbKMQM9amMLio9KMzLtoOmnuj9z0wvA72h1L8oSGbLVqQQbmso4PTXMhFMfc14we03",
"",
null,
null
);
如果我使用下面的方法调用,
return jenkinsAPIClient.doHttpPost(url, EmptyString, jenkinsAPIClient.successStatusCheck, jenkinsAPIClient.GenericExceptionHandler);
测试用例失败并出现以下错误
Argument(s) are different! Wanted:
APIClient#0 bean.doHttpPost(
<any string>,
<any string>,
<any java.util.function.BiFunction>,
<any java.util.function.Consumer>
);
testcasename(ServiceTests.java:435)
Actual invocations have different arguments:
APIClient#0 bean.doHttpPost(
"nulljob/CL217R/job/One/doRename?newName=aYbf8y8FRirlgXQoz7ySNhQqNp870xY0tZ9O6sSSBlbfgktoM7zb3UNdMNbKMQM9amMLio9KMzLtoOmnuj9z0wvA72h1L8oSGbLVqQQbmso4PTXMhFMfc14we03",
"",
null,
APIClient$$Lambda$128/2000563893@360bc645
);
【问题讨论】:
-
欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 以了解如何提高问题的质量。然后edit你的问题包含你的源代码作为minimal reproducible example,它可以被其他人编译和测试。