Difference between @Mock, @MockBean and Mockito.mock()

Viewed 122538

When creating tests and mocking dependencies, what is the difference between these three approaches?

  1. @MockBean:

    @MockBean
    MyService myservice;
    
  2. @Mock:

    @Mock
    MyService myservice;
    
  3. Mockito.mock()

    MyService myservice = Mockito.mock(MyService.class);
    
3 Answers

Mocktio.mock() :-

  1. Will create a mock object of either class or interface. We can use this mock to stub the return values and verify if they are called.
  2. We must use the when(..) and thenReturn(..) methods for mock objects whose class methods will be invoked during test case execution.

@Mock :-

  1. This is shorthand for mock() method so it is preferable and often used.
  2. Both mock() and @Mock are functionally equivalent.
  3. Easier to identify the problem in mock failure as name of the field appears in the error message.

To enable the Mockito annotation during test execution we need to call the MockitoAnnotations.initMocks(this) method but this method is deprecated instead we can call - MockitoAnnotations.openMocks(this). In order to avoid the side effects it is advised to call this method before test case executions.

Another way to enable the Mockito annotations is by annotating the test class with @RunWith by specifying the MockitoJUnitRunner that does this task and also other useful things.

@MockBean :- It is used to add the mock objects into spring application context. This mock will replace the existing bean of same type in application context. If no bean is available, then new bean will be added. This is useful in integration test case.

When we write a test case that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is used and it is fast and favors the isolation of the tested component.

If our test case needs to rely on the Spring Boot container and want to add or mock one of the container beans then @MockBean is used.

Related