@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 } }
This creates a MockHttpServletRequest
that is send to the @RestContoller
servlets.
Problem: my servlets make use of HttpServletRequest.getServletPath()
, but which is always empty using the WebTestClient
approach above.
Question: how can I explicit set the servletPath
in my junit tests?
Advertisement
Answer
I could solve it as follows, but as this is really hacky, I’d still appreciate a proper solution.
@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); }; } }