无法用Mockito模拟Spring 'RestTemplate'交换方法

tktrz96b  于 2022-11-08  发布在  Spring
关注(0)|答案(1)|浏览(165)

这是我的选拔赛
java

when(restTemplate.exchange(
            Mockito.<String>eq("http://some.api.asmx"),
            Mockito.<HttpMethod>eq(HttpMethod.POST),
            Mockito.<HttpEntity<List<Object>>>any(),
            Mockito.<ParameterizedTypeReference<SuchenResponse>>any())).thenReturn(Mockito.<ResponseEntity>any());

这总是会失败

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 2 recorded:
-> at com.myapp.sst.base.app.service.ServiceTest.shouldDo(ServiceTest.java:62)
-> at com.myapp.sst.base.app.service.ServiceTest.shouldDo(ServiceTest.java:63)

然而,我对每个参数都使用了eqany,所以不应该发生这个错误,对吗?

fnx2tebb

fnx2tebb1#

您正在使用thenReturn中的Mockito.<ResponseEntity>any()
在这里,您应该指定当restTemplate调用发生时mockito应该返回什么,例如ResponseEntityBuilder.builderOK().build()
也许与其模仿RestTemplate,不如尝试使用类似的MockRestServiceServer

private MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build()

mockServer.expect(ExpectedCount.between(0, Integer.MAX_VALUE), requestTo("http://some.api.asmx"))
            .andExpect(method(HttpMethod.POST))
            .andRespond(withStatus(HttpStatus.OK))

相关问题