我有方法:
public void loadPlatformDependencies() {
try {
dependenciesRepository.deleteAll();
dependenciesRepository.saveAll(pullLastDependencies());
publisher.publishEvent(new LoadedDependenciesEvent());
} catch (Exception e) {
LOGGER.error("Failed to load dependencies", e);
}
}
我尝试测试它:
@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());
}
但是有一个问题,该方法 pullLastDependency() 现在工作不正确。我有一个错误:
Invalid use of argument matchers!
0 matchers expectd, 1 recorded:
方法 pullLastDependency() 返回列表。 我可以在没有正常工作的方法 pullLastDependency() 的情况下测试此方法吗?或者也许我应该以另一种方式测试这个方法?
最佳答案
您在 when()
中使用捕获器,而不是 verify()
。
并且您从模拟方法中返回 any()
(即null
),而不是返回您希望此模拟返回的内容。如果你不关心它返回什么,因为你不使用它,那么返回一个空的迭代。
应该是
when(dependenciesRepository.saveAll(any()).thenReturn(Collections.emptyList());
puller.loadPlatformDependencies();
verify(dependenciesRepository).deleteAll();
verify(dependenciesRepository).saveAll(captor.capture());
关于java - 参数匹配器的使用无效。如果此方法使用另一个私有(private)方法,我该如何测试它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436366/