'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 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1