gpt4 book ai didi

java - 如何在 Spring WebClient 中验证请求 url?

转载 作者:行者123 更新时间:2023-12-02 01:00:54 24 4
gpt4 key购买 nike

我有一个 WebClient,想要验证 Web 客户端发送的 urlpayload。但是我如何在 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 方法中。

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>

关于java - 如何在 Spring WebClient 中验证请求 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60654316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com