多年后回到Java / Spring . 试图开发控制器测试 . 我想测试OPTIONS请求的处理程序,但是当我使用MockMvc做类似的事情时
MockHttpServletRequestBuilder optionsRequest = options("/endpoint/1234");
optionsRequest.header("Origin", "http://blah");
this.mockMvc.perform(optionsRequest).
andExpect(status().isOk()).
andExpect(header().string("Access-Control-Allow-Credentials", "application/json")).
andExpect(header().string("Access-Control-Allow-Origin", "application/json")).
andExpect(header().string("Access-Control-Allow-Methods", "application/json")).
andExpect(header().string("Access-Control-Allow-Headers", "application/json"));
与设置
this.mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
其中 controller
是我的控制器的一个实例,选项处理程序永远不会被触发 .
在我的服务器启动中,我们需要这样做
dispatcherServlet.setDispatchOptionsRequest(true);
获取正在运行的应用程序中处理的请求 .
有没有办法在测试设置中访问调度程序servlet,以便我可以设置相同的选项?
我已经退回到设置模拟请求/响应对象并立即手动调用方法....
1 回答
您只需使用该选项创建
MockMvc
对象即可Here's javadoc .