🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
🚀 Introduction: Why is @MockBean Deprecated?
For years, @MockBean has been widely used in Spring Boot unit tests to mock dependencies. However, in Spring Boot 3.2, @MockBean has been deprecated due to performance and maintainability concerns.
🔴 Problems with @MockBean
✔ Creates unnecessary Spring context proxies → Slows down test execution.
✔ Mocks beans globally → Can cause side effects in multiple tests.
✔ Not optimized for Spring Boot 3.2 testing improvements.
✅ Solution: Use @MockitoBean
Spring Boot 3.2 introduces @MockitoBean, which provides:
✔ Faster test execution with direct Mockito integration.
✔ Better isolation of test components.
✔ More reliable unit testing experience.
1️⃣ What is @MockitoBean?
@MockitoBean is a new annotation in Spring Boot 3.2 that acts as a direct replacement for @MockBean.
✔ It creates mock instances for dependencies.
✔ It integrates better with JUnit 5 and Mockito.
✔ It does not require full Spring context reloading.
2️⃣ Replacing @MockBean with @MockitoBean
Let’s take an example where we mock a repository in a service test.
📝 Example 1: Old Approach Using @MockBean (Deprecated)
@SpringBootTest
class UserServiceTest {
@MockBean // ❌ Deprecated in Spring Boot 3.2+
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
void testGetUserById() {
User mockUser = new User(1L, "John Doe");
Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
User result = userService.getUserById(1L);
assertEquals("John Doe", result.getName());
}
}
❌ Issues with @MockBean in this approach:
- Requires Spring Context initialization, making tests slower.
- Affects other tests due to global mocking.
✅ Example 2: New Approach Using @MockitoBean (Spring Boot 3.2+)
@SpringBootTest
class UserServiceTest {
@MockitoBean // ✅ New Recommended Annotation
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
void testGetUserById() {
User mockUser = new User(1L, "John Doe");
Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
User result = userService.getUserById(1L);
assertEquals("John Doe", result.getName());
}
}
✅ Benefits of using @MockitoBean
✔ Faster execution – Does not reload the Spring Context.
✔ Scoped mocking – Mocks only in the test class.
✔ More stable unit testing experience.
3️⃣ Unit Testing a REST Controller with @MockitoBean and MockMvc
Spring Boot also allows testing REST controllers without starting the full application.
✅ Example: Testing UserController
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean // ✅ Mock only in this test class
private UserService userService;
@Test
void testGetUserById() throws Exception {
User mockUser = new User(1L, "John Doe");
Mockito.when(userService.getUserById(1L)).thenReturn(mockUser);
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John Doe"));
}
}
✅ Uses MockMvc to test API endpoints efficiently.
✅ Mocks UserService without loading the full application.
4️⃣ Key Differences: @MockBean vs. @MockitoBean
| Feature | @MockBean (Deprecated) |
@MockitoBean (Recommended) |
|---|---|---|
| Spring Boot Version | Before 3.2 | 3.2+ |
| Performance | Slower (requires Spring Context) | Faster (Mockito direct integration) |
| Scope | Global (affects multiple tests) | Local (scoped per test) |
| Mockito Integration | Uses Spring proxies | Directly integrates with Mockito |
| Recommended? | ❌ No | ✅ Yes |
🚀 Always use @MockitoBean in Spring Boot 3.2+ for unit tests!
5️⃣ Best Practices for Unit Testing in Spring Boot 3.2+
✔ Use @MockitoBean instead of @MockBean for faster tests.
✔ Use @WebMvcTest for controller testing.
✔ Use @SpringBootTest only for integration tests.
✔ Mock dependencies instead of using real DB connections.
✔ Use Mockito.when() and verify() to validate method calls.
🎯 Conclusion: Why Switch to @MockitoBean?
By switching to @MockitoBean, you get:
✅ Faster test execution (no Spring Context reloads).
✅ Better test isolation (per-test mock scope).
✅ More efficient Mockito integration.
🚀 Are you using @MockitoBean in your Spring Boot 3.2+ projects? Comment below!
🔗 Share this guide with developers to help them migrate from @MockBean to @MockitoBean! 🚀
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment