如何通过MockMvc为每个请求设置servlet路径 [英] How to set servlet path for every request through MockMvc

查看:514
本文介绍了如何通过MockMvc为每个请求设置servlet路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为通过MockMvc的所有请求(获取,发布,放置,删除)设置servlet路径?

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

Spring分派servlet映射到/rest/* 但是在测试中,我必须删除url中的/rest部分,否则Spring测试无法识别控制器.

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.

编辑

@Sotirios:

@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 .

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.

还是只能通过standaloneSetup定义ServletPath?

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

推荐答案

我遇到了ServletException("Circular view path ...")的问题,该问题仅在实际部署中发生,而在我们使用MockMvc进行的测试中从未发生过.

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

问题在于方法未使用@ResponseBody进行注释.该测试运行良好,因为servlet路径为空,因此将viewName解析为与"callPath"不同的"servletPath/callPath",因此没有引发ServletException.因此,我需要在测试请求上设置ServletPath,以更接近应用程序的部署方式,并使我们的测试失败,以防万一忘记了注释.

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.

这篇关于如何通过MockMvc为每个请求设置servlet路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆