考虑这个示例类:
public class Processor {
private final Dependency dependency;
public Processor(Dependency dependency) {
this.dependency = dependency;
}
public void processUsers(List<Integer> userIds, int attempt) {
if (attempt == 0) {
//log initial processing
} else if (attempt > 0 && attempt < 5) {
//log retry processing
} else {
//log processing limit exceeded
return;
}
List<Integer> failedIds = new ArrayList<Integer>();
for (Integer userId : userIds) {
try {
processUser(userId);
} catch (Exception ex) {
//logging
failedIds.add(userId);
}
}
if (failedIds.isEmpty()) {
//log ok
} else {
processUsers(failedIds, attempt + 1);
}
}
public void processUser(Integer userId) throws Exception{
//dependency can throw exception
dependency.call();
}
}
我想验证processUsers
抛出异常时该方法调用自身。这是我的暴躁测试:
public class ProcessorTest {
@Test
public void processShouldCallItselfWithFailedSublistWhenProcessingFails(){
Dependency dependency = mock(Dependency.class);
when(dependency.call()).thenThrow(Exception.class);
Processor processor = new Processor(dependency);
processor.processUsers(Arrays.asList(new Integer[]{1,2,3}), 0);
//need to verify processor will call #processUsers recursively
//because the dependency thrown Exception, how?
}
}
在某些情况下,验证该方法以递归方式调用自身的最佳实践是什么?
我正在使用 TestNG + Mockito 和这种冗长的语言称为JAVA