【发布时间】:2020-03-13 01:02:44
【问题描述】:
关于模拟 WebClient 对象,有几个问题提供了有用的答案。但是我在用身体发帖时仍然遇到问题。我只是使用 Mockito 而不是 mockwebserver。
这是我正在测试的方法:
public class RestClient extends BaseRestClient {
...
public <T,G> Mono<T> post(String url, G req, Class<T> resp) throws IOException {
Mono<T> response = null;
response = this.getWebClient().post()
.uri(url)
.header(HttpHeaders.CONTENT_TYPE,JSON_CONTENT_TYPE)
.accept(MediaType.APPLICATION_JSON)
//.body(BodyInserters.fromObject(req))
.header(HttpHeaders.AUTHORIZATION, BEARER + token)
.retrieve()
.bodyToMono(resp).log();
return response.map(resp::cast);
}
...
注意注释掉的正文行。
这是与上面的代码一起正常工作的测试——再次注意测试中注释掉的行:
@Mock
WebClient webClient;
@Mock
WebClient.RequestBodyUriSpec requestBodyUriSpec;
@Mock
WebClient.RequestHeadersSpec requestHeadersSpec;
@Mock
WebClient.RequestBodySpec requestBodySpec;
@Mock
WebClient.ResponseSpec responseSpec;
@InjectMocks
RestClient restClient;
@Test
public void postTest() throws IOException {
when(webClient.post()).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec);
when(requestBodySpec.header(any(),any())).thenReturn(requestBodySpec);
when(requestBodySpec.accept(any())).thenReturn(requestBodySpec);
when(responseSpec.bodyToMono(ArgumentMatchers.<Class<String>>notNull()))
.thenReturn(Mono.just("resp"));
//when(requestBodySpec.body(any())).thenReturn(requestHeadersSpec);
when(requestBodySpec.retrieve()).thenReturn(responseSpec);
restClient.post("http://sampleurl",Object.class, Object.class);
}
再次,一切正常。但是,如果我将注释掉的行放回代码中,这意味着这篇文章有一个正文,并通过将注释掉的行放回测试中来模拟正文,那么我将获得 NullPointerException .retrieve() 在代码中。就像我缺少要模拟的对象一样。
我什至为 requestHeadersSpec 和 requestBodyUriSpec 模拟了 .retrieve():
when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
when(requestBodyUriSpec.retrieve()).thenReturn(responseSpec);
仍然没有成功。有什么想法吗?
【问题讨论】:
-
完全模拟
webclient太可怕了,但这是唯一的方法 -
是的,不能同意更多:)
-
有时问题可能是导入
org.junit.jupiter.api.Test而不是org.junit.Test;
标签: java spring unit-testing mockito webclient