我正在尝试使用mockito为Spring Boot中的Rest Client编写Junit测试用例。在模拟响应时出现错误,如下所示:
使用 Mockito 进行模拟响应:
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(Url);
Mockito.when(this.restTlsTemplate
.exchange(Mockito.eq(builder.toString()), HttpMethod.GET, Mockito.any(), RestResponse.class)
.getBody()).thenReturn(response());
获取上述模拟响应时出错:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 2 recorded:
-> at (ApplicationTests.java:54)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
任何人都可以检查一下并帮助我解决这个问题。
最佳答案
如果您对 stub 或验证方法调用中的参数之一使用匹配器,例如 Mockito.eq
或 Mockito.any
,则必须使用匹配器所有参数。这是因为 Mockito 在内部堆栈中排列其匹配器的方式。所以你应该写
Mockito.when(this.restTlsTemplate
.exchange(Mockito.eq(builder.toString()), Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(RestResponse.class))
.getBody()).thenReturn(response());
其中 Mockito.eq
已放置在您想要精确匹配的每个参数周围。
关于java - Spring Boot 中 Rest Client Junit 的 InvalidUseOfMatchersException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62255726/