0
0
SpringbootHow-ToBeginner · 4 min read

How to Use @MockBean in Spring Boot for Unit Testing

Use @MockBean in Spring Boot tests to replace a bean in the application context with a mock instance. This allows you to isolate the class under test by mocking its dependencies easily within @SpringBootTest or other Spring test annotations.
📐

Syntax

The @MockBean annotation is placed on a field in a Spring Boot test class. It tells Spring to create a mock of the specified type and replace any existing bean of that type in the application context.

  • @MockBean: Marks the field as a mock bean.
  • Field type: The class or interface to mock.
  • Field name: The variable name for the mock instance.
java
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyServiceTest {

    @MockBean
    private MyRepository myRepository;

    // test methods here
}
💻

Example

This example shows how to use @MockBean to mock a repository inside a service test. The mock replaces the real repository bean, so you can control its behavior and test the service logic in isolation.

java
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
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    @Test
    public void testGetUserName() {
        // Arrange: mock repository to return a user
        User mockUser = new User(1L, "Alice");
        given(userRepository.findById(1L)).willReturn(java.util.Optional.of(mockUser));

        // Act: call service method
        String name = userService.getUserName(1L);

        // Assert: verify service returns mocked user name
        assertThat(name).isEqualTo("Alice");
    }
}

// Supporting classes
class User {
    private Long id;
    private String name;

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

interface UserRepository {
    java.util.Optional<User> findById(Long id);
}

class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public String getUserName(Long id) {
        return userRepository.findById(id).map(User::getName).orElse(null);
    }
}
Output
Test passes with no errors, confirming the service returns 'Alice' from the mocked repository.
⚠️

Common Pitfalls

Common mistakes when using @MockBean include:

  • Not using @SpringBootTest or a Spring test annotation that loads the context, so mocks are not injected.
  • Mocking a bean that is not part of the application context, causing no replacement.
  • Forgetting to configure mock behavior, leading to null or default returns.
  • Mixing @MockBean with manual mock creation without proper injection.
java
/* Wrong: No Spring context, so @MockBean has no effect */
public class WrongTest {
    @MockBean
    private MyService myService; // This will not be injected
}

/* Right: Use @SpringBootTest to enable context and injection */
@SpringBootTest
public class RightTest {
    @MockBean
    private MyService myService; // Properly injected mock
}
📊

Quick Reference

  • @MockBean: Replaces a bean in Spring context with a Mockito mock.
  • Use inside @SpringBootTest or similar test annotations.
  • Mock behavior with Mockito methods like given() or when().
  • Helps isolate the class under test by mocking dependencies.

Key Takeaways

Use @MockBean to replace Spring beans with mocks in test contexts.
Always run tests with @SpringBootTest or similar to enable mock injection.
Configure mock behavior to control dependency responses during tests.
Avoid using @MockBean outside Spring test contexts as it won't work.
MockBean helps isolate units by mocking dependencies automatically.