我有一个方法,需要测试它:
void update() {
_cleaner.clear();
_updator.upadate();
}
调用的顺序对于这个场景很重要。我想这样写测试:
void updateTest(){
Integer CLEAR = 0, UPDATE = 1;
Stack<Integer> callStack = new Stack<>();
Cleaner cleaner = mock(Cleaner.class);
Updator updator = mock(Updator.class);
when(cleaner.clear()).callback(() -> callStack.add(CLEAR));
when(updator.update()).callback(() -> callStack.add(UPDATE));
Some testingObj = new Some(cleaner, updator);
testingObj.update();
assertEquels(CLEAR, callStack.pop());
assertEquels(UPDATE, callStack.pop());
assertTrue(callStack.isEmpty());
}
_cleaner.clear()和_update . update()返回void。很明显
when(cleaner.clear()).callback(() -> callStack.add(ClearCall));
when(updator.update()).callback(() -> callStack.add(UpdateCall));
是无效代码。除了那些成功的台词,我还能写些什么呢?如何设置回调方法(以void为结果类型)由mockito调用?
我建议您使用InOrder
验证器来确认这些方法是按照您想要的顺序调用的。查看这里的一些文档:http://site.mockito.org/mockito/docs/current/org/mockito/InOrder.html
这个例子是基于直接来自该文档的代码:
InOrder inOrder = inOrder(cleaner, updator);
inOrder.verify(cleaner).clear();
inOrder.verify(updator).update();