简体   繁体   中英

How to validate request url in Spring WebClient?

I have a WebClient and want to validate the url and the payload that the webclient has send. But how can I get access to it in a junit integration test? Means: how can I record them?

@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?
   }
}

I think you can use MockWebServer library. I prepared a small demo to test your method. Of course, for multiple test cases, you can put the MockWebServer initialization to an @BeforeAll method, and the shutdown to an @AfterAll method.

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();
    }

}

To use MockWebServer, you need the following dependencies.

        <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM