我有一个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>

09-10 23:46