Bird
Raised Fist0
Spring Bootframework~10 mins

@MockBean for mocking dependencies in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @MockBean for mocking dependencies
Start Test
↓
Spring Context Loads
↓
@MockBean Creates Mock
↓
Inject Mock into Context
↓
Test Runs Using Mock
↓
Verify Behavior or Output
↓
Test Ends
The test starts by loading Spring context, then @MockBean creates a mock object and injects it into the context, replacing the real bean. The test runs using this mock, allowing controlled behavior and verification.
Execution Sample
Spring Boot
@MockBean
private UserService userService;

@Test
void testGetUser() {
  when(userService.getUser()).thenReturn(new User("Alice"));
  String name = userService.getUser().getName();
  assertEquals("Alice", name);
}
This test mocks UserService, sets a return value for getUser(), calls it, and checks the returned name.
Execution Table
StepActionMock StateMethod CalledReturn ValueTest Assertion
1@MockBean creates mock UserServiceUserService mock creatednonenonenone
2when(userService.getUser()).thenReturn(new User("Alice"))Stub set for getUser()nonenonenone
3Call userService.getUser()Stub activegetUser()User("Alice")none
4Call getName() on returned UserStub activegetName()"Alice"none
5assertEquals("Alice", name)Stub activenonenonePass
6Test endsMock cleanednonenoneTest success
💡 Test ends after assertion passes using mocked UserService
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
userServicenullmock objectmock objectmock objectmock object
namenullnullUser("Alice")"Alice""Alice"
Key Moments - 2 Insights
Why does userService.getUser() return a User object even though userService is a mock?
Because at step 2 in the execution_table, we set a stub with when(...).thenReturn(...), telling the mock what to return when getUser() is called.
Does @MockBean replace the real bean in the Spring context?
Yes, as shown in the concept_flow, @MockBean creates a mock and injects it into the Spring context, replacing the real bean for the test.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3. What does userService.getUser() return?
AUser("Alice") from the mock
BA real User from the database
Cnull
DAn exception
💡 Hint
Check the 'Return Value' column at step 3 in the execution_table.
At which step is the stub for getUser() set on the mock?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look for when(...).thenReturn(...) in the 'Action' column of the execution_table.
If we remove @MockBean, what would happen to the test?
ATest would still use the mock
BTest would fail to start Spring context
CTest would use the real UserService bean
DTest would pass without any changes
💡 Hint
Refer to the concept_flow about how @MockBean replaces the real bean in the context.
Concept Snapshot
@MockBean creates a mock of a Spring bean and injects it into the test context.
Use when(...).thenReturn(...) to define mock behavior.
The mock replaces the real bean during tests.
This allows isolated testing without real dependencies.
Assertions verify expected mock interactions or outputs.
Full Transcript
In Spring Boot tests, @MockBean creates a mock object of a bean and injects it into the Spring context, replacing the real bean. This lets tests control and verify the behavior of dependencies. The test sets up the mock's behavior using when(...).thenReturn(...). When the test calls methods on the mock, it returns the stubbed values. Assertions check these returned values to confirm correct behavior. This approach isolates the unit under test from real dependencies, making tests faster and more reliable.

Practice

(1/5)
1. What is the main purpose of using @MockBean in a Spring Boot test?
easy
A. To replace a real Spring bean with a mock for isolated testing
B. To create a new Spring bean in the application context
C. To automatically inject real dependencies into the test
D. To configure database connections for integration tests

Solution

  1. Step 1: Understand the role of @MockBean

    @MockBean is used to replace a real bean in the Spring context with a mock version during tests.
  2. Step 2: Identify the testing benefit

    This replacement helps isolate the component under test by faking dependencies, avoiding real implementations.
  3. Final Answer:

    To replace a real Spring bean with a mock for isolated testing -> Option A
  4. Quick Check:

    @MockBean replaces real beans [OK]
Hint: Remember: @MockBean fakes dependencies for focused tests [OK]
Common Mistakes:
  • Thinking @MockBean creates new beans instead of replacing
  • Confusing @MockBean with @Autowired injection
  • Using @MockBean to configure real database connections
2. Which of the following is the correct way to declare a mock bean for a service named UserService in a Spring Boot test?
easy
A. @MockBean UserService userService = new UserService();
B. @MockBean private UserService userService;
C. @MockBean public void userService();
D. @MockBean UserService userService();

Solution

  1. Step 1: Recall @MockBean declaration syntax

    @MockBean is used as an annotation on a field to create a mock instance injected by Spring.
  2. Step 2: Check each option

    @MockBean private UserService userService; correctly declares a private field annotated with @MockBean. Other options use invalid syntax such as instantiating manually with new or declaring as methods.
  3. Final Answer:

    @MockBean private UserService userService; -> Option B
  4. Quick Check:

    @MockBean on private field [OK]
Hint: Use @MockBean on private fields only [OK]
Common Mistakes:
  • Trying to instantiate mock manually with new
  • Declaring @MockBean on methods instead of fields
  • Omitting access modifier or using invalid syntax
3. Given this test snippet:
@MockBean
private PaymentService paymentService;

@Test
void testProcess() {
  when(paymentService.pay()).thenReturn(true);
  boolean result = paymentService.pay();
  System.out.println(result);
}

What will be printed when the test runs?
medium
A. null
B. false
C. true
D. Exception thrown

Solution

  1. Step 1: Understand mocking behavior

    The mock paymentService is told to return true when pay() is called using when().thenReturn(true).
  2. Step 2: Trace the method call

    Calling paymentService.pay() returns true as configured, so result is true and printed.
  3. Final Answer:

    true -> Option C
  4. Quick Check:

    Mock returns configured value = true [OK]
Hint: Mock returns what you tell it with when().thenReturn() [OK]
Common Mistakes:
  • Expecting default false instead of configured true
  • Confusing mock with real implementation output
  • Not setting up when().thenReturn() before call
4. Consider this test code snippet:
@MockBean
private OrderService orderService;

@Test
void testOrder() {
  orderService.placeOrder();
  verify(orderService).placeOrder();
}

When running this test, it fails with a NullPointerException. What is the most likely cause?
medium
A. The orderService is not mocked properly because it is private
B. The verify method is called before placeOrder()
C. The placeOrder() method is final and cannot be mocked
D. The @MockBean annotation was not processed because the test class lacks @SpringBootTest

Solution

  1. Step 1: Check test setup requirements

    @MockBean requires Spring Boot test context to process annotations, usually via @SpringBootTest or similar.
  2. Step 2: Identify cause of NullPointerException

    If @MockBean is not processed, orderService remains null, causing NPE when calling placeOrder().
  3. Final Answer:

    The @MockBean annotation was not processed because the test class lacks @SpringBootTest -> Option D
  4. Quick Check:

    @MockBean needs Spring context [OK]
Hint: Always use @SpringBootTest to enable @MockBean processing [OK]
Common Mistakes:
  • Assuming private fields can't be mocked
  • Misordering verify and method calls
  • Not realizing final methods can't be mocked (but not cause NPE here)
5. 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?
hard
A. Use @MockBean EmailSender emailSender; in the test class, call notificationService.notify(), then verify with verify(emailSender, times(1)).sendEmail();
B. Use @Autowired EmailSender emailSender; and call sendEmail() directly in the test
C. Create a new EmailSender instance manually and inject it into NotificationService
D. Use @MockBean NotificationService notificationService; and verify sendEmail() on it

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]
Hint: 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard