When to use and not use @Mock annotation, @MockBean annotation, @InjectMock annotation & @Autowired annotation in a spring webflux reactive project
Asked Answered
T

1

12

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;
Tamis answered 3/4, 2022 at 8:30 Comment(0)
A
20

@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.
Adelric answered 3/4, 2022 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.