Video in progress
How do you test a controller with Spring Security enabled using @WebMvcTest?
You bring in the security configuration with @Import, provide the user with @WithMockUser or .with(user(...)) / .with(jwt()), and add .with(csrf()) to POSTs where needed. Then you check 200, 401 and 403 separately.
📖 Answer
@WebMvcTest(RefundController.class)
@Import(SecurityConfig.class) // load our own rules
class RefundControllerTest {
@Autowired MockMvc mvc;
@MockitoBean RefundService service;
@Test
void anonymousGets401() throws Exception {
mvc.perform(post("/api/refunds/7"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "OPERATOR")
void operatorCannotRefund() throws Exception {
mvc.perform(post("/api/refunds/7").with(csrf()))
.andExpect(status().isForbidden());
}
@Test
void adminCanRefund() throws Exception {
mvc.perform(post("/api/refunds/7")
.with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isOk());
verify(service).refund(7L);
}
}
What to watch for:
@Import: a slice test loads only the web layer. If yourSecurityConfigisn't loaded, Boot's default security applies and the tests end up checking different rules. Mock whatever beans the configuration depends on (for example,JwtDecoder);- CSRF: in an application with sessions, POSTs without
csrf()give 403, and that gets confused with "role not sufficient". In a stateless JWT API CSRF is usually off, so you don't needcsrf(); jwt(): it doesn't build a real token, it puts aJwtAuthenticationTokenin directly. This test doesn't cover the token signature verification logic;@PreAuthorize: if method security is on (@EnableMethodSecurity), it works in these tests too, because the controller is a real bean.
For every important endpoint, write all three cases (anonymous, unauthorized, authorized): if someone changes a rule without understanding it, these tests are the first to catch it.
Sign up to mark studied questions and save your progress.