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