I'm migrating a few tests from MockMvc to WebTestClient.

Unfortunately the following cannot be refactored, as there is no RequestAttribute setter in WebTestClient.

@Test
public void test() {
    String body = mvc.perform(MockMvcRequestBuilders.get("/error?format=csv")
            .requestAttr(RequestDispatcher.ERROR_EXCEPTION, new RestClientException("junit"))
            .requestAttr(RequestDispatcher.ERROR_MESSAGE, "csv error"))
            .andReturn()
            .getResponse()
            .getContentAsString();

    assertEquals("csv error", body);
}

with application.properties:

spring.mvc.contentnegotiation.media-types.csv=text/plain

Would be great if RequestAttribute could also be set in WebTestClient!

Comment From: bclozel

Have you tried org.springframework.test.web.reactive.server.WebTestClient.RequestHeadersSpec#attribute?

Comment From: membersound

Yes of course. The following equivalent fails:

webTestClient.get()
    .uri("/error?format=csv")
    .attribute(RequestDispatcher.ERROR_EXCEPTION, new RestClientException("junit"))
    .attribute(RequestDispatcher.ERROR_MESSAGE, "csv error")
    .exchange()
    .expectBody(String.class)
    .returnResult().getResponseBody();

assertEquals("csv error", body);

Result

org.opentest4j.AssertionFailedError: 
Expected :csv error
Actual   :No message available

Comment From: bclozel

Sorry, I got confused here.

Indeed, MockMvc's requestAttr are meant as Servlet request attributes (so, as in the Servlet container). WebTestClient attributes are local to the request on the client side and are never sent over the wire; they can be used in ExchangeFilterFunction. In summary, those are different concepts.

Just like in #28051 - we're facing here a conceptual difference between MockMvc and WebTestClient. The first one drives the exchange from the server side and can act on server concepts. The latter drives tests from the client side and cannot drive server behavior since the prepared request could be sent over the wire: this is why we can use the same API against a live server with a real transport, which is not the case with MockMvc.

I'll close this issue as a known limitation of that approach. While we've enabled WebTestClient "over MockMvc", this doesn't mean that this is a replacement nor that it should cover all MockMvc features.