The @MockitoBean annotation allows us to replace a bean in the Spring test's ApplicationContext with a Mockito mock (check out this tutorial)). This is useful when we want to isolate the component under test by mocking its dependencies.
Why Use @MockitoBean?
In integration tests, we often need to test a component while controlling the behavior of its dependencies. @MockitoBean provides several benefits:
- Replaces real beans with mocks in the test context
- Allows stubbing specific behaviors for testing different scenarios
- Creates new beans if they don't exist (REPLACE_OR_CREATE strategy)
- Integrates seamlessly with Spring's dependency injection
Java source and doc
Definition of MockitoBeanVersion: 7.0.4 package org.springframework.test.context.bean.override.mockito;
@Target({ ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(MockitoBeans.class)
@BeanOverride(MockitoBeanOverrideProcessor.class)
public @interface MockitoBean {
@AliasFor("name")
String value() default ""; 1
@AliasFor("value")
String name() default ""; 2
Class<?>[] types() default {}; 3
String contextName() default ""; 4
Class<?>[] extraInterfaces() default {}; 5
Answers answers() default Answers.RETURNS_DEFAULTS; 6
boolean serializable() default false; 7
MockReset reset() default MockReset.AFTER; 8
boolean enforceOverride() default false; 9
}
Example
Service Classes
First, let's create a repository and a service that depends on it:
package com.logicbig.example;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository {
String findUserById(String id);
}
package com.logicbig.example;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String getUser(String id) {
return userRepository.findUserById(id);
}
}
Configuration
The configuration class registers our beans:
package com.logicbig.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {
}
Test with @MockitoBean
Now we'll test the service by mocking the repository:
package com.logicbig.example;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SpringJUnitConfig(AppConfig.class)
public class MockitoBeanTest {
@MockitoBean
UserRepository userRepository;
@Autowired
UserService userService;
@Test
public void testWithMockedRepository() {
when(userRepository.findUserById("123")).thenReturn("Mocked user");
String result = userService.getUser("123");
System.out.println("Result: " + result);
verify(userRepository).findUserById("123");
assertEquals("Mocked user", result);
}
}
Output$ mvn test [INFO] Scanning for projects... [INFO] [INFO] -----------------< com.logicbig.example:mockito-bean >------------------ [INFO] Building mockito-bean 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- dependency:3.6.1:properties (default) @ mockito-bean --- [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ mockito-bean --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-core-testing\mockito-bean\src\main\resources [INFO] [INFO] --- compiler:3.13.0:compile (default-compile) @ mockito-bean --- [INFO] Nothing to compile - all classes are up to date. [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ mockito-bean --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-core-testing\mockito-bean\src\test\resources [INFO] [INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ mockito-bean --- [INFO] Recompiling the module because of added or removed source files. [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 1 source file with javac [debug target 21] to target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ mockito-bean --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.MockitoBeanTest Result: Mocked user [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.998 s -- in com.logicbig.example.MockitoBeanTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 14.858 s [INFO] Finished at: 2026-02-12T00:56:33+08:00 [INFO] ------------------------------------------------------------------------
Conclusion
The output confirms that @MockitoBean successfully replaced the real UserRepository with a mock. The stubbed behavior returned our test data instead of the real implementation's result. This demonstrates how @MockitoBean enables isolated testing by controlling dependency behavior through Mockito mocking.
Example ProjectDependencies and Technologies Used: - spring-context 7.0.4 (Spring Context)
Version Compatibility: 6.2.0 - 7.0.4 Version compatibilities of spring-context with this example:
- 6.2.0
- 6.2.1
- 6.2.2
- 6.2.3
- 6.2.4
- 6.2.5
- 6.2.6
- 6.2.7
- 6.2.8
- 6.2.9
- 6.2.10
- 6.2.11
- 6.2.12
- 6.2.13
- 6.2.14
- 6.2.15
- 6.2.16
- 7.0.0
- 7.0.1
- 7.0.2
- 7.0.3
- 7.0.4
Versions in green have been tested.
- spring-test 7.0.4 (Spring TestContext Framework)
- junit-jupiter-engine 6.0.2 (Module "junit-jupiter-engine" of JUnit)
- mockito-core 5.20.0 (Mockito mock objects library core API and implementation)
- JDK 21
- Maven 3.9.11
|