Spring使用MockMvc Test和CORS过滤器

时间:2017-09-25 12:23:23

标签: spring spring-test spring-test-mvc

我正在尝试运行基本的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中发出请求,这样就不会引发关于“标题值不能为空”的错误。

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

1 个答案:

答案 0 :(得分:2)

java.lang.IllegalArgumentException:标头值不能为null。所以使用.header(key,value)传递标头值,如下所示:

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