Issue
I have a requirement to test my service layer in Micronaut. I am using bean validation in my service layer and so I need validator to be injected in the testing phase and I can't just mock it. However, I want to mock some other classes and so I am also using Mockito as well.
The problem is if I am putting @MicornautTest on my class all the beans marked with @Inject are Not-Null which means that @Inject is working fine. However, as soon as I add @ExtendWith(MockitoExtension.class) to the class and re-run the tests, all the means marked with @Inject are now null and all the beans marked with @Mock are Not-Null.
So it looks like either I can use @Inject in my tests or I can use @Mock but not both.
@MicronautTest
@ExtendWith(MockitoExtension.class)
class CashServiceTest {
@Inject
private Validator validator;
@Mock
private AvailableCashClient availableCashClient;
Has anyone faced similar issue earlier? Can you please guide me the correct configuration which will allow me to use both @Inject and @Mock in the same tests.
Solution
I was able to find the issue and was able to use both mocked beans and original injected beans. The issue is we should not use @ExtendWith annotation and can achieve everything just by using @micronaut test.
I am pasting code for the set up which I did. In this case, BusinessClient is the bean which is being mocked and Validator is the bean which is injected without being mocked.
@MicronautTest class CashServiceTest {
@Inject
AvailableCashClient availableCashClient;
@Inject
Validator validator;
@MockBean(AvailableCashClient)
public AvailableCashClient availableCashClient() {
return Mockito.mock(AvailableCashClient);
}
Answered By - Pulkit Gupta