nerdexam
Broadcom-VMware

2V0-72.22PSE · Question #61

In a Spring test, which annotation can be used to mock a user?

The correct answer is B. @WithMockUser. @WithMockUser (B) is the correct Spring Security Test annotation that simulates an authenticated user in your test context - it injects a mock Authentication object into the SecurityContextHolder, letting you test secured endpoints without a real user in the database. @Mock (C)…

Testing

Question

In a Spring test, which annotation can be used to mock a user?

Options

  • A@MockAuthentication
  • B@WithMockUser
  • C@Mock
  • D@MockBean

How the community answered

(19 responses)
  • A
    5% (1)
  • B
    89% (17)
  • C
    5% (1)

Explanation

@WithMockUser (B) is the correct Spring Security Test annotation that simulates an authenticated user in your test context - it injects a mock Authentication object into the SecurityContextHolder, letting you test secured endpoints without a real user in the database. @Mock (C) is a Mockito annotation for creating mock objects of any class and has no awareness of Spring Security's authentication context. @MockBean (D) is a Spring Boot testing annotation that replaces a Spring bean in the application context with a Mockito mock, also unrelated to authentication. @MockAuthentication (A) does not exist in any standard Spring or Spring Security library - it's a plausible-sounding distractor.

Memory tip: Think "With Mock User" - the annotation literally reads like a sentence: "run this test with a mock user." If you can hear the phrase, you've got the annotation.

Topics

#Spring Security#@WithMockUser#Mock User#Test Authentication

Community Discussion

No community discussion yet for this question.

Full 2V0-72.22PSE Practice