I have am trying to run a basic MVC test
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
However, this will always result in java.lang.IllegalArgumentException: Header value must not be null
I found out that if I deactivate the CORS filter the test will work without errors.
My 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);
}
}
Part of my Security Config
@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);
}
}
Only if I remove the @Component in the SimpleCORSFilter and remove the line .addFilterBefore(new SimpleCORS...)
in SecurityConfig the test works.
How can I use mockMVC in my test? Either how do I disable the CORSFilter for the test or how do I make the request in mockMvc correctly so it doesn't throw an error about "header value must not be null".
I have tried setting a random header value in the mockMvc but that didn't change the error.
java.lang.IllegalArgumentException: Header value must not be null.so pass the header value using .header(key,value) like below:
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/").header("Origin","*")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With