[英]How to validate request url in Spring WebClient?
我有一个WebClient
并且想要验证 webclient 发送的url
和payload
。 但是如何在junit
集成测试中访问它? 意思是:我怎样才能记录它们?
@Service
public class RestService {
@Autowired
private WebClient web;
public Mono<String> send() {
web.post().uri("/test").bodyValue("testval").retrieve().bodyToMono(String.class);
}
}
@SpringBootTest
public class RestServiceITest {
@Autowired
private RestService service;
@Test
public void testUrl() {
service.send();
//TODO how to validate the request uri + body the the webClient received?
}
}
我认为您可以使用 MockWebServer 库。 我准备了一个小演示来测试你的方法。 当然,对于多个测试用例,可以将 MockWebServer 初始化放在一个@BeforeAll
方法中,将关闭@AfterAll
一个@AfterAll
方法中。
class RestServiceTest {
@Test
@SneakyThrows
public void testSend() {
MockWebServer server = new MockWebServer();
// Schedule some responses.
server.enqueue(new MockResponse().setBody("hello, world!"));
// Start the server.
server.start();
String baseUrl = String.format("http://localhost:%s", server.getPort());
// initialize a WebClient with the base url of the mock server
final WebClient webClient = WebClient.builder().baseUrl(baseUrl).build();
// initialize our service class
final RestService restService = new RestService(webClient);
// send the request
final String sendResponse = restService.send().block();
// ASSERTIONS
assertNotNull(sendResponse);
assertEquals("hello, world!", sendResponse);
// get the recorded request data
RecordedRequest request = server.takeRequest();
assertEquals("testval", request.getBody().readUtf8());
assertEquals("POST", request.getMethod());
assertEquals("/test", request.getPath());
server.shutdown();
}
}
要使用 MockWebServer,您需要以下依赖项。
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>4.0.1</version>
<scope>test</scope>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.