How to redirect redirect mock requests in Spring MVC REST test?

巧了我就是萌 提交于 2019-12-07 18:34:27

You will notice when you setup your MockMvc configuration that you don't specify the location of a deployment descriptor, your web.xml. That is because MockMvc doesn't test your configuration of a DispatcherServlet. It tests your MVC configuration, @Controller beans and the like.

If you look at the source, MockMvc creates a TestDispatcherServlet which loads and uses your web application context.

In other words, the servlet url-pattern path is irrelevant to MockMvc. You make your requests as if there was no such path.

You state

I hope to map the controller in test like in actual scenario.

you will need to use a different test strategy. Fully deploy your web application and use an HTTP client to make requests and validate what you get back.

You've tagged unit-testing. Testing in a full environment is not unit testing, it is integration and system testing.


Note that this

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/api/**").addResourceLocations("/");
}

has nothing to do with the above. Its purpose is to serve static resources from some path in your webapp. It has nothing to do with your servlet's url-pattern or the path to your controllers.

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