I tried with mockito-inline and it doesn't work in my case.
Class BankService {
//BankService will autowire 2 repositories, say bankRepo and fundRepo;
public Fund onMessage(Object obj){
Processor processor = ProcessorFactory.getProcessor(obj.getAccountType());
processor.process(obj);
//rest of logic
}
}
Class ProcessorFactory {
public Processor getProcessor(String accountType){
switch(accountType) {
case "A": return new AProcessor();
case "B": return new BProcessor();
//rest of the logic, simple switch
}
}
}
@ExtendsWith(MockitoExtension.class)
Class BankTest {
@Mock
BankRepository bankRepo;
@Mock
Aprocessor mockProcessor;
@Mock
FundRepository fundRepo;
@InjectMock
BankService bankService;
@Test
public void onMessage(){
when(bankRepo)...
when(fundRepo)...
//Now how can I mock ProcessorFactory in bankService?
try(MockStatic mock = mockStatic(ProcessorFactory.class)) {
//Strangely the assertThat statement passed, so it means it does return a mockProcessor.
when(() -> ProcessorFactory.getProcessor(any())).thenReturn(mockProcessor);
assertThat(ProcessorFactory.getProcessor(any())).isEqualTo(mockProcessor);
//However, when onMessage is called, ProcessorFactory.getProcessor return an actual object, not mockProcessor
bankService.onMessage(obj);
}
}
}
I know junit4 has powermock and prepareForTest and I've done static mocking before in junit4. However for this project, I can only use junit5, and I can't change the code.
If I don't have a mock object returned from ProcessorFactory, it will be very difficult to test because these processors calls many other services and db operations. I know it is not ideal, but that is what I have.
Any help will be appreciated. Thanks in advance.