2

First of all, its important to specify that the app is already deployed and our spring security configuration works. If an unauthenticated user tries to access to any endpoint of the API it returns 401 Unauthorized.

Following, this sample example, I want to test a Controller with @WebMvcTest and spring security

@WebMvcTest(EmployeeController.class)   
@Import(SecurityConfig.class)
class EmployeeControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    protected MockMvc mvc;

    @MockBean
    private EmployeeService service;

    @BeforeEach
    public void setUp() {
        this.mvc = MockMvcBuilders
                .webAppContextSetup(ctx)
                .apply(springSecurity())
                .build();
    }

    @Test
    void unauthorized_role_should_return_401() {

       mvc.perform(get("/employees/1").accept(MediaType.APPLICATION_JSON)
            .with(SecurityMockMvcRequestPostProcessors.user("manager").roles("UNKNOWN")))
            .andExpect(status().isUnauthorized())
    }
}

This code works, but I don't understand why I need to import the SecurityConfig class to the test class. Indeed, if I remove the @Import, mockMvc returns 200. But, every sample project that I found over Github simply use @WebMvcTest even if the project has a SecurityConfig class

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
Pierre Jones
  • 620
  • 1
  • 11
  • 24

1 Answers1

4

There is no need to configure extra thing in order to enable spring security when using @WebMvcTest as @WebMvcTest will enable it automatically.

But if you customise the spring-security by creating your own beans , you still have to define these customised beans for the tests for the customisation to work. @Import is one of the way to define these beans. By consolidating their configuration into a SecurityConfig , it can keep your test cases DRY because if a test case need to test with the security stuff , it just need to import this SecurityConfig rather repeatedly do the same configuration for each test.

So it is rather a code design decision which is an application specific and hence it is normal that not every project will have the same kind of setup.

Ken Chan
  • 84,777
  • 26
  • 143
  • 172