Reputation: 642
I have method:
public void loadPlatformDependencies() {
try {
dependenciesRepository.deleteAll();
dependenciesRepository.saveAll(pullLastDependencies());
publisher.publishEvent(new LoadedDependenciesEvent());
} catch (Exception e) {
LOGGER.error("Failed to load dependencies", e);
}
}
And I try to test it:
@Test
public void testLoadPlatformDependencies() {
ArgumentCaptor<Iterable<Dependency>> captor = ArgumentCaptor.forClass(Iterable.class);
when(dependenciesRepository.saveAll(captor.capture())).thenReturn(any(Iterable.class));
puller.loadPlatformDependencies();
verify(dependenciesRepository,times(1)).deleteAll();
verify(dependenciesRepository, times(1)).saveAll(any(Iterable.class));
verify(publisher,times(1)).publishEvent(any());
}
But there is a problem, that method pullLastDependencies() work incorect now. I have a mistake:
Invalid use of argument matchers!
0 matchers expectd, 1 recorded:
Method pullLastDependencies() returns List. Can I test this method without a properly working method pullLastDependencies()? Or maybe I should test this method in another way?
Upvotes: 5
Views: 1258
Reputation: 9
I think the problem here is that you are using a matcher as a return value in
when(dependenciesRepository.saveAll(captor.capture())).thenReturn(any(Iterable.class));
You should use the matchers to "match" method parameters, and return another structure, like this:
when(dependenciesRepository.saveAll(anyIterable())).thenReturn(Collections.emptyList())
As long as your pullLastDependencies() method doesn't have another dependency, it should work.
Edit: It seems that your pullLastDependencies() has some other dependencies, so you need to mock the call to it. You can achieve this by changing the visibility of the method during the test, so you can mock it, but keep in mind that this is not considered good pratice.
//making private method accessible
Method method = service.getClass().getDeclaredMethod("pullLastDependencies",params);
method .setAccessible(true);
when(pullLastDependencies()).thenReturn(Collections.emptyList())
Upvotes: -1
Reputation: 692081
You're using the captor in when()
instead of verify()
.
And you're returning any()
(which is just null
) from your mocked method, instead of returning what you want this mock to return. if you don't care about what it returns because you don't use it, then return an empty iterable.
It should be
when(dependenciesRepository.saveAll(any()).thenReturn(Collections.emptyList());
puller.loadPlatformDependencies();
verify(dependenciesRepository).deleteAll();
verify(dependenciesRepository).saveAll(captor.capture());
Upvotes: 2