@Mock vs. @MockBean in Spring Boot Testing

When it comes to testing Spring Boot applications, the framework provides powerful annotations to simplify the mocking of dependencies. Two such annotations are @Mock (from the Mockito framework) and @MockBean (from the Spring framework). While they might seem similar at first glance, they serve different purposes and are used in distinct contexts. In this blog post, we'll dive into the nuances of @Mock and @MockBean, helping developers understand when and how to use each annotation effectively.

What is @Mock? 

@Mock is an annotation provided by the Mockito testing framework, one of the most popular mocking libraries in the Java ecosystem. It is used to create mock objects for the classes you want to isolate from the tests. 

Key Characteristics of @Mock: 

Purpose: @Mock creates a simple mock object that can be used in any testing scenario, not just in the Spring context. 

Usage: It’s typically used in unit tests where you're testing a class in isolation. 


public class SomeServiceTest {

    private Dependency dependency;

    private SomeService someService;

    // ... Test methods ...

What is @MockBean? 

@MockBean is a Spring-specific annotation used in integration testing. It adds mock objects to the Spring application context. 

Key Characteristics of @MockBean: 

Spring Context: @MockBean is used when you need to add or replace a bean in the Spring context with a mock. 

Usage: Ideal for integration tests where you want to test the interaction with the Spring context but mock out specific beans. 

public class SomeServiceIntegrationTest {

    private Dependency dependency;

    private SomeService someService;

    // ... Test methods ...
Here, Dependency is a mock within the Spring context, and SomeService is a Spring bean being tested.

@Mock vs. @MockBean: When to Use Which? 

Use @Mock for Unit Testing: When writing unit tests that focus on a single class and its methods, without loading the Spring context, use @Mock. 

Use @MockBean for Integration Testing or Unit Testing Spring MVC controllers: When writing integration tests where you need the Spring context, and you want to replace a bean in the application context with a mock, use @MockBean. You can also use @MockBean while unit Testing Spring MVC controllers.


Differences between @Mock and @MockBean

Feature @Mock @MockBean
Usage Scope Used for creating mock objects in standard unit tests without Spring context. Specific to Spring Boot for adding/replacing beans in the Spring application context.
Test Type Ideal for unit tests to test classes in isolation. Suited for integration tests with necessary interactions within the Spring context.