SpringBoot @WebMvcTest security issue

Imran picture Imran · Jul 15, 2017 · Viewed 7.2k times · Source

I have a spring rest mvc controller which has the url "/public/rest/vehicle/get". In my security configuration, I have defined that any requests for /public/rest should not require authentication.

    http.
             csrf().disable()
            .authorizeRequests()
            .antMatchers("/home/**", "/**", "/css/**", "/js/**", "/fonts/**", "/images/**", "/public/rest/**","/login*","/signin/**","/signup/**").permitAll()
            .antMatchers("/property/**").authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .and().httpBasic().disable();

This configuration works fine when I start my application and submit request using browser or any other mean. Now, I have a test class which looks like this,

@RunWith(SpringRunner.class)
@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private VehicleService vehicleService;


    @Test
    public void getVehicle() throws Exception {
       given(this.vehicleService.get(0)).
               willReturn(new VehicleEquipmentDTO());
        this.mockMvc.perform(get("/public/rest/vehicle/get").param("id","0"))
                .andDo(print())
                .andExpect(status().isOk());//.andExpect(content().string("Honda Civic"));
    }}

Now, when I run this test, it says

java.lang.AssertionError: Status 
Expected :200
Actual   :401

When I print the request response, I see it is complaining because of security. "Error message = Full authentication is required to access this resource" Any ideas why it is not working with the security config that I have, and what is the work around to force it to use the correct configurations? Thanks in advance

Answer

Imran picture Imran · Jul 15, 2017

Finally found the reason. Since WebMvcTest is only sliced testing, it would not take the security configurations. The work around is to explicitly import it like,

@Import(WebSecurityConfig.class)