Search code examples
javaspringspring-bootspring-boot-test

How to resolve the Exception from WebTestClient?


How can I achieve the following with WebTestClient?

@Autowired
private MockMvc mvc;

mvc.perform(req)
        .andExpect(status)
        .andReturn().getResolvedException();

This is quite not the same, how can I actually resolve the Exception?

@Autowired
private WebTestClient webTestClient;

webTestClient.post()
       .exchange()
       .returnResult(String.class)
       .getResponseBody();

Solution

  • While the following works, I don't know if it's the correct way:

    ...
    .expectBody()
    .consumeWith(res -> {
        Exception ex = ((MvcResult) res.getMockServerResult()).getResolvedException();
        assertEquals(ex instanceof MyException.class);
        assertEquals("Hello Exception", ex.getMessage());
    })
    

    Note this only works when having the spring-web dependency on classpath. Having only spring-webflux, this would fail as .getMockServerResult() is always null then.