首页 > 解决方案 > Spring Boot 中 Rest Client Junit 的 InvalidUseOfMatchersException

问题描述

我正在尝试在 Spring Boot 中使用 mockito 为 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"));

任何人都可以检查这个并帮助我。

标签: javaspring-bootmockitojunit5

解决方案


如果您对存根或验证方法调用中的参数之一使用匹配器,例如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());

whereMockito.eq已放置在您要精确匹配的每个参数周围。


推荐阅读