0
0
JUnittesting~5 mins

@MockBean for Spring mocking in JUnit

Choose your learning style9 modes available
Introduction

@MockBean helps replace real Spring beans with fake ones during tests. This lets you test parts of your app without running everything.

When you want to test a service but avoid calling the real database.
When you want to fake a web service call inside your Spring app.
When you want to isolate a component and control its dependencies during tests.
When you want to simulate different responses from a dependency without changing real code.
Syntax
JUnit
@MockBean
private YourDependency yourDependency;

Place @MockBean on a field inside a Spring test class.

Spring replaces the real bean with this mock during the test.

Examples
This mocks the UserRepository bean so you can fake database calls.
JUnit
@MockBean
private UserRepository userRepository;
This mocks the EmailService bean to fake sending emails during tests.
JUnit
@MockBean
private EmailService emailService;
Sample Program

This test replaces the real UserRepository with a mock. It fakes the method findNameById to return "Alice". Then it checks if UserService returns "Alice" for user id 1.

JUnit
import static org.mockito.BDDMockito.given;
import static org.assertj.core.api.Assertions.assertThat;

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;

@SpringBootTest
class UserServiceTest {

    @MockBean
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Test
    void testFindUserName() {
        given(userRepository.findNameById(1L)).willReturn("Alice");

        String name = userService.getUserName(1L);

        assertThat(name).isEqualTo("Alice");
    }
}

// UserService.java
// public String getUserName(Long id) {
//     return userRepository.findNameById(id);
// }

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

@MockBean works only in Spring test contexts like @SpringBootTest.

Mocks created by @MockBean are automatically injected into Spring beans.

Use Mockito methods like given(), when(), verify() to control mock behavior.

Summary

@MockBean replaces real Spring beans with mocks during tests.

It helps isolate parts of your app and avoid calling real dependencies.

Use it inside Spring test classes to control dependencies easily.