Mockito
@Mock
@MockBean
Java Testing
Unit Testing

Difference between Mock, MockBean and Mockito.mock

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

When working with unit testing in Java applications, particularly those that use Spring Framework and Mockito, developers frequently encounter @Mock, @MockBean, and Mockito.mock(). Each of these has its own use cases and implications. Understanding the differences can streamline the testing process, making it more effective and precise.

Overview of @Mock, @MockBean, and Mockito.mock()

@Mock

@Mock is an annotation from the Mockito library used for creating mock objects. It is typically utilized in conjunction with @RunWith(MockitoJUnitRunner.class) or by initializing the Mockito annotations with MockitoAnnotations.initMocks(this) in the setup method.

  • Purpose: To create a mock object for a given class or interface, enabling isolation from external dependencies during testing.
  • Usage:
java
1  import org.junit.Before;
2  import org.junit.Test;
3  import org.junit.runner.RunWith;
4  import org.mockito.InjectMocks;
5  import org.mockito.Mock;
6  import org.mockito.MockitoAnnotations;
7  import org.mockito.junit.MockitoJUnitRunner;
8
9  @RunWith(MockitoJUnitRunner.class)
10  public class ExampleTest {
11  
12      @Mock
13      private Dependency dependencyMock;
14  
15      @InjectMocks
16      private ClassUnderTest classUnderTest;
17  
18      @Before
19      public void setUp() {
20          MockitoAnnotations.initMocks(this);
21      }
22  
23      @Test
24      public void testMethod() {
25          // Use dependencyMock to perform test
26      }
27  }
  • Environment: Purely Mockito/Java based, without dependency on Spring.

@MockBean

@MockBean is specific to the Spring Boot testing framework. It is a Spring-specific variant that facilitates mocking in a Spring application context, ensuring that the mock objects are injected into the Spring context.

  • Purpose: To create a mock bean within the Spring ApplicationContext, primarily for use in integration tests or when you want to control the behavior of a bean within a Spring-managed test.
  • Usage:
java
1  import org.junit.jupiter.api.Test;
2  import org.springframework.beans.factory.annotation.Autowired;
3  import org.springframework.boot.test.context.SpringBootTest;
4  import org.springframework.boot.test.mock.mockito.MockBean;
5  
6  @SpringBootTest
7  public class SpringBootExampleTest {
8  
9      @MockBean
10      private Dependency dependencyMock;
11  
12      @Autowired
13      private ClassUnderTest classUnderTest;
14  
15      @Test
16      public void testMethod() {
17          // dependencyMock is now a part of Spring's ApplicationContext
18      }
19  }
  • Environment: Requires Spring context, specifically useful within a @SpringBootTest.

Mockito.mock()

Mockito.mock() is a static method from the Mockito library that provides an alternative to the @Mock annotation for creating mock objects programmatically within test methods.

  • Purpose: To create mock objects with a specific setup that may not necessarily require an annotation-driven approach.
  • Usage:
java
1  import org.junit.Test;
2  import org.mockito.Mockito;
3
4  public class StaticMockExampleTest {
5  
6      private final Dependency dependencyMock = Mockito.mock(Dependency.class);
7  
8      @Test
9      public void testMethod() {
10          ClassUnderTest classUnderTest = new ClassUnderTest(dependencyMock);
11          // Test classUnderTest with dependencyMock
12      }
13  }
  • Environment: Mockito/Java based, no dependency on Spring or additional annotations.

Differences at a Glance

Feature/Aspect@Mock@MockBeanMockito.mock()
LibraryMockitoSpring Boot + MockitoMockito
Application ContextNot requiredRequiredNot required
PurposeIsolate unit testsMock beans in a Spring contextProgrammatically create mocks
Initialization@RunWith or initMocks()Automatically managed by SpringDirect method call
Usage ScenarioUnit testsSpring integration testsAny testing scenario
FlexibilityAnnotation-based, less flexibleSpring-dependantFlexible method-based

Considerations for Use

  1. Use @Mock or Mockito.mock() for Unit Testing - When the goal is to isolate the unit test from external dependencies without involving the Spring ecosystem, @Mock and Mockito.mock() are preferable. @Mock is annotation-driven and suits tests leveraging MockitoJUnitRunner. Mockito.mock(), on the other hand, is straightforward for smaller tests where initMocks() feels excessive.
  2. Use @MockBean for Integration Tests within Spring Context - When writing tests that deal with Spring's application context or require the application bootstrapping provided by Spring Boot (e.g., @SpringBootTest), @MockBean is essential. It allows replacing parts of the context that are otherwise integrated, such as data repositories or service beans, with controlled mock instances.
  3. Mock Configuration - While all three approaches mock behavior in a similar fashion, the way they are configured and the environments they target vary significantly. Understanding the testing context (unit vs. integration) greatly guides which approach to use.

By selecting the appropriate mocking strategy based on the testing scenario and environment setup, developers can ensure more maintainable, reliable, and efficient tests.


Course illustration
Course illustration

All Rights Reserved.