0
0
Spring Bootframework~5 mins

@MockBean for mocking dependencies in Spring Boot

Choose your learning style9 modes available
Introduction

@MockBean helps you replace real parts of your app with fake ones during tests. This way, you can test one part without worrying about others.

When you want to test a service without calling the real database.
When you need to fake a web service call inside your app during tests.
When you want to isolate a component and avoid side effects from its dependencies.
When you want to control the behavior of a dependency to test different scenarios.
When you want to speed up tests by avoiding slow or complex real dependencies.
Syntax
Spring Boot
@MockBean
private DependencyType dependency;
Place @MockBean on a field inside a Spring Boot test class.
Spring Boot will replace the real bean with this mock during the test.
Examples
This mocks the UserRepository bean so you can fake database calls in tests.
Spring Boot
@MockBean
private UserRepository userRepository;
This replaces the real EmailService with a mock to avoid sending real emails during tests.
Spring Boot
@MockBean
private EmailService emailService;
Sample Program

This test mocks UserRepository to return "Alice" when asked for user 1. The UserService uses this mock, so the test prints "Alice" without needing a real database.

Spring Boot
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.mockito.Mockito.*;

@SpringBootTest
public class UserServiceTest {

    @MockBean
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Test
    public void testGetUserName() {
        when(userRepository.findNameById(1L)).thenReturn("Alice");

        String name = userService.getUserName(1L);

        System.out.println(name);
    }
}

// UserService.java
// public class UserService {
//     @Autowired
//     private UserRepository userRepository;
//     public String getUserName(Long id) {
//         return userRepository.findNameById(id);
//     }
// }

// UserRepository.java
// public interface UserRepository {
//     String findNameById(Long id);
// }
OutputSuccess
Important Notes

Use @MockBean only in Spring Boot test classes annotated with @SpringBootTest or similar.

Mocks created by @MockBean are automatically injected into the Spring context, replacing real beans.

Remember to import Mockito static methods like when() and verify() to control mock behavior.

Summary

@MockBean replaces real beans with mocks during tests.

It helps isolate the part you want to test by faking dependencies.

Use it to control dependency behavior and avoid side effects in tests.