2014-02-17 28 views
4

是否可以为所有通过MockMvc的请求(get,post,put,delete)设置servlet路径?如何通过MockMvc为每个请求设置servlet路径

Spring调度servlet映射到/ rest/* 但是在我的测试中,我必须删除url中的/ rest部分,否则Spring测试不会识别控制器。

编辑

@Sotirios:

东西是可能的,如:

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(); 

}}

但我不知道怎么路径servlet可以为所有请求进行设置。以上代码来自http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html

还是只能用standaloneSetup定义servletPath?

+1

当您在setup()方法中构建MockMVC时将contextPath和servletPath设置为defaultRequest的一部分时,它确实会应用于所有请求。即使使用webAppContextSetup,也可以使用,而不仅仅是standaloneSetup。 – ami91

回答

3

我遇到了ServletException(“Circular view path ...”)的问题,它只发生在真正的部署中,但从未在我们的MockMvc测试中发生。

问题是一个方法没有用@ResponseBody注释。测试工作正常,因为有一个空的servlet路径,因此它将viewName解析为'servletPath/callPath',它与'callPath'不同,因此它不会抛出ServletException。因此,我需要在测试请求上设置servletPath以更接近应用程序的部署方式,并在我们忘记注释的情况下让我们的测试失败。

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

为我工作就像一个魅力。所以这个问题的答案是有效的。