Bird
Raised Fist0
Spring Bootframework~20 mins

@MockBean for mocking dependencies in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mocking Mastery with @MockBean
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when @MockBean is used on a service in a Spring Boot test?
Consider a Spring Boot test class where a service is annotated with @MockBean. What is the effect of this annotation on the application context during the test?
Spring Boot
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserServiceTest {

    @MockBean
    private UserRepository userRepository;

    // test methods
}
AThe UserRepository bean is disabled and no bean is available in the test context.
BThe real UserRepository bean is replaced by a Mockito mock in the test context.
CA new instance of UserRepository is created without any mocking.
DThe UserRepository bean is proxied but calls go to the real implementation.
Attempts:
2 left
💡 Hint
Think about how Spring Boot replaces beans during testing to isolate dependencies.
📝 Syntax
intermediate
2:00remaining
Identify the correct way to declare a @MockBean in a Spring Boot test
Which of the following code snippets correctly declares a @MockBean for a service in a Spring Boot test class?
A
@MockBean
private UserService userService;
B
@MockBean
UserService userService = new UserService();
C
@MockBean
public UserService userService() { return new UserService(); }
D
@MockBean(UserService.class)
private UserService userService;
Attempts:
2 left
💡 Hint
Remember how fields are annotated for mocking in Spring Boot tests.
🔧 Debug
advanced
2:00remaining
Why does the test fail to inject the mocked bean with @MockBean?
Given the following test code, the test fails because the mocked bean is not injected properly. What is the most likely cause?
 @SpringBootTest
public class OrderServiceTest {

    @MockBean
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;

    @Test
    public void testOrder() {
        // test logic
    }
}
AThe PaymentService bean is final and cannot be mocked by Mockito.
BThe @MockBean annotation is missing the required parameter to specify the bean class.
CThe test class is missing @ExtendWith(MockitoExtension.class) annotation.
DThe OrderService bean is not a Spring-managed bean, so injection fails.
Attempts:
2 left
💡 Hint
Check if the service under test is managed by Spring context.
❓ state_output
advanced
2:00remaining
What is the output of the test when using @MockBean with a stubbed method?
Given the following test snippet, what will be the output printed?
 @SpringBootTest
public class GreetingServiceTest {

    @MockBean
    private TimeService timeService;

    @Autowired
    private GreetingService greetingService;

    @Test
    public void testGreeting() {
        when(timeService.getCurrentHour()).thenReturn(10);
        System.out.println(greetingService.greet());
    }
}

// GreetingService calls timeService.getCurrentHour() and returns "Good morning" if hour < 12, else "Good afternoon".
Anull
BGood afternoon
CGood morning
DThrows NullPointerException
Attempts:
2 left
💡 Hint
Consider the stubbed return value of the mocked method.
🧠 Conceptual
expert
3:00remaining
Why use @MockBean instead of Mockito.mock() in Spring Boot tests?
Which of the following best explains the advantage of using @MockBean over directly creating mocks with Mockito.mock() in Spring Boot integration tests?
A@MockBean replaces the bean in the Spring application context, ensuring all dependencies receive the mock automatically.
B@MockBean creates a mock that can only be used in unit tests, not integration tests.
CMockito.mock() automatically registers the mock in the Spring context, so @MockBean is redundant.
D@MockBean disables all other beans except the mocked one, speeding up tests.
Attempts:
2 left
💡 Hint
Think about how Spring manages beans and dependencies during tests.

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