Reputation: 127
I'm newbie in mockito with Spring boot. My problem is that, I use mockito as below with mockbean.
@Autowired
private AnotherService anotherService;
@MockBean
private SchedulerService schedulerService;
@Test
public void test() {
NpMesaj npMesaj = new NpMesaj("npMesaj");
when(schedulerService.schedule(any(NpMesaj.class))).thenThrow(new RuntimeException("Error"));
try {
anotherService.start(npMesaj);
} catch (Exception e) {
}
Optional<NpMesaj> npMesajFromDb = repository.findById(npMesaj.getId());
assertThat("A_Err", npMesajFromDb.isPresent(), is(false));
}
The SchedulerService is used in anotherService.start method. It is mocked in this test scope and my assertion works well. After this test, MY ANOTHER UNIT TEST CLASS as below is executed and it doesn't work. It is not include any mock bean or methods.
// Unit Test-2
@Autowired
private DiffService diffService;
@Test
public void test_2(){
int diff = diffService.startDiffProcess();
assertThat("A_Err", diff, is(0));
}
This test method's startDiffProcess method call also calls anotherService.start method in it, as below:
@Autowired
private AnotherService anotherService;
public int startDiffProcess(){
anotherService.start();
return 0;
}
AnotherService uses SchedulerService as I mention in first test above. When I debug Unit-test-2, the SchedulerService in the AnotherService is seen as mockitoMock with MockInterceptor and cannot execute real method.
What can be the reason of it? Why mock method calls cannot be reset? Thanks.
Upvotes: 0
Views: 2867
Reputation: 9622
This is certainly strange behavior that I have not experienced myself. Are these test classes in the same package?
Either way, in your first test you can mark the class as @DirtiesContext to ensure that the Spring application context used in that test is removed from the context cache. This should prevent the same context being loaded in another test class.
Upvotes: 1