How to redirect redirect mock requests in Spring M

2019-06-03 20:22发布

问题:

In my web.xml I mapped the servlet to /api like this:

<servlet-mapping>
    <servlet-name>todo</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>todo</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

So for the controller using @RequestMapping(value = "/todo", method = RequestMethod.GET), it actually gets mapped to "/api/todo"

But in test when I call mockMvc.perform(get("/api/todo/")) I got a 404. I have to call get("/todo/") to get the correct mapping in test. I hope to map the controller in test like in actual scenario. Is that possible?

I'm using WebMvcConfigurerAdapter in test and I tried

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

but it didn't work.

回答1:

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.