Spring 使用带有 CORS 过滤器的 MockMvc 测试

Spring using MockMvc Test with CORS filter

我正在尝试 运行 一个基本的 MVC 测试

@Test
public void shouldReturnDefaultMessage() throws Exception {
    this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
            .andExpect(content().string(containsString("Hello World")));
}

但是,这总是会导致 java.lang.IllegalArgumentException: Header value must not be null 我发现 如果我停用 CORS 过滤器,测试将正常工作

我的 SimpleCORSFilter

@Component
public class SimpleCORSFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

    public SimpleCORSFilter() {
        log.info("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //...
        chain.doFilter(req, res);
    }

}

我的部分安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsServiceImp userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new SimpleCORSFilter(),UsernamePasswordAuthenticationFilter.class);
    }
}

仅当我删除 SimpleCORSFilter 中的 @Component 并删除 SecurityConfig 中的 .addFilterBefore(new SimpleCORS...) 行时,测试才有效。

如何在测试中使用 mockMVC?我如何为测试禁用 CORSFilter,或者我如何正确地在 mockMvc 中发出请求,这样它就不会抛出关于 "header value must not be null".

的错误

我尝试在 mockMvc 中设置随机 header 值,但这并没有改变错误。

java.lang.IllegalArgumentException:Header 值不能是 null.so 使用 .header(key,value) 传递 header 值,如下所示:

 @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/").header("Origin","*")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }