[英]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.