Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring using MockMvc Test with CORS filter

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.

like image 474
isADon Avatar asked Mar 07 '23 23:03

isADon


1 Answers

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")));
    }
like image 153
Barath Avatar answered Mar 31 '23 12:03

Barath