Bird
0
0

You want to test a controller that uses Spring Security for authentication. Using @WebMvcTest, what additional configuration is needed to test secured endpoints?

hard📝 Conceptual Q8 of 15
Spring Boot - Testing Spring Boot Applications
You want to test a controller that uses Spring Security for authentication. Using @WebMvcTest, what additional configuration is needed to test secured endpoints?
ANo additional configuration is needed; security is disabled by default in @WebMvcTest
BAdd <code>@AutoConfigureMockMvc(addFilters = false)</code> to disable security filters
CAdd <code>@WithMockUser</code> on test methods to simulate an authenticated user
DUse <code>@SpringBootTest</code> instead of <code>@WebMvcTest</code> for security tests
Step-by-Step Solution
Solution:
  1. Step 1: Understand security behavior in @WebMvcTest

    @WebMvcTest loads security filters by default, so secured endpoints require authentication.
  2. Step 2: Use @WithMockUser to simulate authentication

    Adding @WithMockUser on test methods simulates a logged-in user, allowing access to secured endpoints.
  3. Final Answer:

    Add @WithMockUser on test methods to simulate an authenticated user -> Option C
  4. Quick Check:

    Use @WithMockUser to test secured endpoints [OK]
Quick Trick: Use @WithMockUser to simulate login in @WebMvcTest [OK]
Common Mistakes:
  • Disabling security filters instead of mocking user
  • Assuming security is off by default
  • Switching to @SpringBootTest unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes