如何在Spring Junit WebTestClient中设置服务路径()?

91zkwejq  于 2022-10-30  发布在  Spring
关注(0)|答案(2)|浏览(119)
@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
    }
}

这将创建一个发送到@RestContoller servlet的MockHttpServletRequest
问题:我的servlet使用了HttpServletRequest.getServletPath(),但是使用上面的WebTestClient方法时,它总是空的。
问:如何在junit测试中显式设置servletPath

92dk7w1h

92dk7w1h1#

我可以解决它如下,但这是真的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);
        };
    }
}
xqkwcwgp

xqkwcwgp2#

一种解决方案是计算路径:request.getServletPath() returned null from Spring MVC
在测试和生产中为我做了工作。

相关问题