【发布时间】:2013-04-05 13:30:17
【问题描述】:
考虑这个示例类:
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 的冗长语言
【问题讨论】:
-
依赖真的不用userId参数吗?
-
确实如此,只是实际使用的一个例子
标签: java unit-testing mocking mockito