提问人:unknown1101 提问时间:11/16/2023 最后编辑:Lesiakunknown1101 更新时间:11/17/2023 访问量:63
JUnit 的模拟 WebClient
Mock WebClient for JUnit
问:
如何在 JUnit 测试用例中模拟 Web 客户端,以便可以测试以下使用 Web 客户端的方法?
public class Service {
@Autowired
private WebClient webClient;
public Flux<String> callExternal(Request request) throws Exception {
return webClient.post()
.uri(externalAPIUrl)
.accept(MediaType.APPLICATION_JSON)
.body(Mono.just(util.convertRequest(request)), ExpectedRequest.class)
.headers(headers -> headers.add("token",util.getToken()))
.retrieve().bodyToFlux(String.class);
}
}
我试过什么:
public class ServiceTest {
@Mock
private WebClient webClient;
@InjectMocks
Service service;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCallExternal() throws Exception {
MockitoAnnotations.openMocks(this);
Request request = Request.builder().id("1").build();
Flux<String> result = Flux.just("test");
WebClient.RequestBodyUriSpec requestBodyUriSpec = mock(WebClient.RequestBodyUriSpec.class);
WebClient.RequestBodySpec requestBodySpec = mock(WebClient.RequestBodySpec.class);
WebClient.RequestHeadersSpec requestHeadersSpec = mock(WebClient.RequestHeadersSpec.class);
WebClient.ResponseSpec responseSpec = mock(WebClient.ResponseSpec.class);
String externalURL = "external url";
when(webClient.post()).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec);
when(requestBodySpec.contentType(any())).thenReturn(requestBodySpec);
when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
when(responseSpec.onStatus(any(), any())).thenReturn(responseSpec);
when(responseSpec.bodyToFlux(String.class)).thenReturn(result);
Flux<String> serviceResponse = Service.callExternal(request);
assertThat(serviceResponse != null);
}
}
我在服务类中 callExternal() 的 webClient.post() 的第一行从 Web 客户端收到空指针异常。
答: 暂无答案
评论
webClientMock
Service
webClient