Bird
0
0

Which setup correctly uses @MockBean to mock EmailSender and verify sendEmail() was called once during the test?

hard📝 Application Q15 of 15
Spring Boot - Testing Spring Boot Applications
You have a Spring Boot service NotificationService that depends on EmailSender. You want to test NotificationService without sending real emails. Which setup correctly uses @MockBean to mock EmailSender and verify sendEmail() was called once during the test?
AUse <code>@MockBean EmailSender emailSender;</code> in the test class, call <code>notificationService.notify()</code>, then verify with <code>verify(emailSender, times(1)).sendEmail();</code>
BUse <code>@Autowired EmailSender emailSender;</code> and call <code>sendEmail()</code> directly in the test
CCreate a new <code>EmailSender</code> instance manually and inject it into <code>NotificationService</code>
DUse <code>@MockBean NotificationService notificationService;</code> and verify <code>sendEmail()</code> on it
Step-by-Step Solution
Solution:
  1. Step 1: Mock the dependency EmailSender

    Use @MockBean on EmailSender to replace the real bean with a mock in the test context.
  2. Step 2: Call the method under test and verify interaction

    Call notificationService.notify() which uses EmailSender internally, then verify sendEmail() was called once on the mock.
  3. Final Answer:

    Use @MockBean EmailSender emailSender; call notificationService.notify(); verify sendEmail() called once -> Option A
  4. Quick Check:

    Mock dependency, call service, verify mock call [OK]
Quick Trick: Mock dependencies, test service, verify mock interactions [OK]
Common Mistakes:
  • Mocking the service instead of its dependency
  • Manually creating dependency instead of using @MockBean
  • Not verifying the mock method call properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes