@Mock
Used to make Mockito create a mock object.
@InjectMock
When you want Mockito to create an instance of an object and use the mocks annotated with @Mock
as its dependencies.
@AutoWired
Used when you want to autowire a bean from the spring context, works exactly the same as in normal code but can only be used in tests that actually creates an application context, such as tests annotated with @WebMvcTest
or @SpringBootTest
.
@MockBean
Can be used to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. If no bean of the same type is defined, a new one will be added. Often used together with @SpringBootTest
So normally you either:
- Use
@Mock
and @InjectMocks
for running tests without a Spring
context, this is preferred as it's much faster.
- Use
@SpringBootTest
or @SpringMvcTest
to start a spring context together with @MockBean
to create mock objects and @Autowired
to get an instance of class you want to test, the mockbeans will be used for its autowired dependencies. You use this when writing integration tests for code that interact with a database or want to test your REST API controllers.