2017-09-25 90 views
0

我也正在尝试运行一个基本的MVC测试春季使用MockMvc测试与CORS过滤

@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); 
    } 
} 

只有当我删除了@Component在SimpleCORSFilter和删除行.addFilterBefore(new SimpleCORS...)在SecurityConfig试验作品的一部分。

如何在我的测试中使用mockMVC?要么我如何禁用CORSFilter进行测试,或者如何正确地在mockMvc中发出请求,以免引发“头部值不能为空”的错误。

我曾尝试在mockMvc中设置一个随机标题值,但没有更改错误。

回答

1

java.lang.IllegalArgumentException异常:报头值不能null.so通过使用.header(键,值)标头值等如下:

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

我曾尝试首先将任何随机头值。导致相同的错误。添加“起源”,如你所说的工作。谢谢! – isADon