Video in progress

Middle 🌱 Spring

What's the difference between @MockitoBean (formerly @MockBean) and a plain Mockito @Mock?

@Mock is for a plain unit test without Spring. @MockitoBean replaces a real bean in the Spring context with a mock, and every bean that injects it gets the mock too.

📖 Answer

A plain unit test — no Spring, the fastest:

@ExtendWith(MockitoExtension.class)
class PriceServiceTest {
    @Mock TaxClient tax;
    @InjectMocks PriceService service;

    @Test
    void addsTax() {
        when(tax.rate("UZ")).thenReturn(new BigDecimal("0.12"));
        assertThat(service.withTax(new BigDecimal("100"), "UZ")).isEqualByComparingTo("112");
    }
}

In a Spring test, one bean in the context gets replaced:

@SpringBootTest
class CheckoutTest {
    @MockitoBean PaymentGateway gateway; // instead of the real gateway in the context
    @Autowired CheckoutService checkout; // gets the mock inside
}

In Boot 3.4 @MockBean/@SpyBean were deprecated, replaced by Spring Framework's @MockitoBean/@MockitoSpyBean.

Use a plain @Mock whenever you can. If @MockitoBean is used in lots of different combinations, test contexts don't get cached and the whole test suite becomes several times slower.