@MockitoBean and @MockitoSpyBean

@MockitoBean and @MockitoSpyBean are used on test class fields to override beans in the test’s ApplicationContext with a Mockito mock or spy, respectively. In the latter case, the original bean definition is not replaced, but instead an early instance of the bean is captured and wrapped by the spy.

By default, the name of the bean to override is derived from the annotated field’s name, but both annotations allow for a specific name to be provided. Each annotation also defines Mockito-specific attributes to fine-tune the mocking details.

The @MockitoBean annotation uses the REPLACE_OR_CREATE_DEFINITION strategy for test bean overriding.

The @MockitoSpyBean annotation uses the WRAP_BEAN strategy, and the original instance is wrapped in a Mockito spy.

The following example shows how to configure the bean name via @MockitoBean and @MockitoSpyBean:

  • Java

class OverrideBeanTests {

	@MockitoBean(name = "service1")  (1)
	private CustomService mockService;

	@MockitoSpyBean(name = "service2") (2)
	private CustomService spyService; (3)

	// test case body...
}
1 Mark mockService as a Mockito mock override of bean service1 in this test class.
2 Mark spyService as a Mockito spy override of bean service2 in this test class.
3 The fields will be injected with the Mockito mock and spy, respectively.