How to set servlet path for every request through MockMvc

元气小坏坏 提交于 2019-11-30 05:35:41

问题


Is it possible to set the servlet path for all requests (get, post, put, delete) which go through the MockMvc?

The Spring dispatch servlet is mapped to /rest/* But in my test I have to remove the /rest part in the url otherwise Spring test does not recognise the controller.

EDIT

@Sotirios:

Something is possible like:

public class MyWebTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = standaloneSetup(new AccountController())
            .defaultRequest(get("/")
            .contextPath("/app").servletPath("/main")
            .accept(MediaType.APPLICATION_JSON).build();

} }

But I wonder how servlet path can be set for all requests. Above code is from http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html.

Or is it only possible to define the servletPath with the standaloneSetup?


回答1:


I've had problems with ServletException("Circular view path ...") which happened only in real deployment but never in our tests with MockMvc.

The problem was that a method was not annotated with @ResponseBody. The test worked fine as there was an empty servlet path so it resolved a viewName to 'servletPath/callPath' which was different from 'callPath' so it did not throw the ServletException. Hence I needed to set servletPath on test requests to get closer to how the app is deployed and get our tests to fail in case one forgets the annotation.

.defaultRequest(get("/").servletPath("/main")) 

worked for me like a charm. So the answer in the question works.



来源:https://stackoverflow.com/questions/21837872/how-to-set-servlet-path-for-every-request-through-mockmvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!