4

I have my SpringBootTest setup like this

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ControllerTest {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void postTest() {
        // Setup data
        Form form = new Form();
        form.setName("Test1");
        form.setDescription("Description1");

        // Run method
        webTestClient.post()
                .uri("/api/v1/data")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .syncBody(form)
                .exchange()

                .expectStatus()
                .isOk()

                .expectBody()
                .jsonPath("data.id").isNotEmpty()
                .jsonPath("data.name").isEqualTo(form.getName())
                .jsonPath("data.description").isEqualTo(form.getDescription())
                .jsonPath("data.status").isEqualTo("A");
    }
}

I cannot work out a way of making the WebTestClient log out all of the HTTP requests and responses.

I would like to leave the WebTestClient as @Autowired. There is probably some sort of application config or configuration class I could create to do this but unfortunately I have not found out how.

matthew.kempson
  • 1,014
  • 1
  • 12
  • 23
  • 1
    @thomas77 The issue there is that they are instantiating the `WebTestClient` manually whereas I would like to keep it `@Autowired` in – matthew.kempson Mar 15 '18 at 15:50

1 Answers1

0

Use ExchangeFilterFunction. See this post how to log webclient call.

Create your own client with the registered filter and it should work.

thomas77
  • 1,100
  • 13
  • 27
  • 2
    The issue there is that they are instantiating the `WebTestClient` manually whereas I would like to keep it `@Autowired` in – matthew.kempson Mar 15 '18 at 15:51
  • Then it should be created and configured in a `@Configuration` class as a bean, so it can be autowired? Do you have any Spring config where you create beans? If so, put it there with the `@Bean` annotation. – thomas77 Mar 15 '18 at 16:00
  • In case you're using spring boot's `@AutoConfigureWebTestClient` you can use a [WebTestClientBuilderCustomizer](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/web/reactive/server/WebTestClientBuilderCustomizer.html) bean to add your filters and stuff. – dtrunk Aug 17 '22 at 12:43