6

我最初实现了一个控制器来处理 OPTIONS 请求并将 CORS 所需的标头应用于响应。最近我一直在清理代码并为 CORS 的东西创建了一个拦截器。该清理的一部分是删除 OPTIONS 请求的控制器方法。

但是,我的 mockmvc 测试需要 OPTIONS 处理方法,而当我实际运行应用程序时,拦截器链会处理 OPTIONS 请求,即使 OPTIONS 请求没有控制器方法也是如此。

我期待这样的测试

MockHttpServletRequestBuilder optionsRequest = options("the-url");

this.mockMvc.perform(optionsRequest).
    andExpect(status().isOk()).
    andExpect(header().string("Access-Control-Allow-Origin", "*")).
    andExpect(header().string("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT")).
    andExpect(header().string("Access-Control-Allow-Headers", "content-type"));

如果我的测试设置有通过

StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(this.controller);
builder = builder.dispatchOptions(true);
builder = builder.addInterceptors(new CorsInterceptor());

或者我希望我不会看到跨源请求在正在运行的应用程序上工作。

4

0 回答 0