javaspringspring-webfluxproject-reactorspringmockito

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


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;

Solution

  • @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: