Home > Back-end >  When to use and not use @Mock annotation, @MockBean annotation, @InjectMock annotation & @Autowired
When to use and not use @Mock annotation, @MockBean annotation, @InjectMock annotation & @Autowired

Time:04-04

Can you please explain when to use below annotations and when not to use those. I am pretty new to testing frameworks and confused with all the answers in the web.

@Mock
private Resource resource;
@MockBean
private Resource resource;
@InjectMock
private ProductService productService; 
@AutoWired
Private ProductRepository productRepo;

CodePudding user response:

@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 mockeans 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.
  • Related