2017-09-25 39 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