如何在 Spring Junit WebTestClient 中设置 ServletPath()?

How to setServletPath() in Spring Junit WebTestClient?

@SpringBootTest(properties = "spring.mvc.servlet.path=/test/path")
@AutoConfigureMockMvc
public class MyTest {
   @Autowired
   private WebTestClient webTestClient

   @Test
   public void test() {
       webTestClient.post()
                .uri(URL)
                .bodyValue(json)
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class)
                .returnResult()
                .getResponseBody();
   }
}

@RestController
public class MyController {    
    @PostMapping
    public Object post(HttpServletRequest req) {
        System.out.println(req.getServletPath()); //always empty in tests
    }
}

这会创建一个 MockHttpServletRequest 发送到 @RestContoller servlet。

问题:我的 servlet 使用 HttpServletRequest.getServletPath(),但使用上述 WebTestClient 方法时它始终为空。

问题:如何在我的 junit 测试中显式设置 servletPath

我可以按如下方式解决它,但由于这真的很 hacky,我仍然希望有一个合适的解决方案。

@TestConfiguration
static class ServletPathMockConfiguration {
    @Bean
    public Filter filter() {
        return (request, response, filterchain) -> {
            Object req = request;
            while (req instanceof ServletRequestWrapper) {
                req = ((ServletRequestWrapper) req).getRequest();
            }
            
            if (req instanceof MockHttpServletRequest)
                ((MockHttpServletRequest) req).setServletPath("/junit/mock/path");

            filterchain.doFilter(request, response);
        };
    }
}