如何通过mockito设置模拟对象方法调用的回调?

时间:2016-10-05 21:11:43

标签: java unit-testing callback mockito

我有方法并需要测试它:

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()和_updator.upadate()返回void。很明显

when(cleaner.clear()).callback(() -> callStack.add(ClearCall)); 
when(updator.update()).callback(() -> callStack.add(UpdateCall));

是无效代码。除了成功之外,我能写些什么?如何通过mockito调用方法的回调(使用void作为结果类型)?

1 个答案:

答案 0 :(得分:1)

我建议您使用- hosts: dev remote_user: JenkinsUser become_method: sudo become_user: TargetUser2 tasks: - command: whoami 验证程序确认按所需顺序调用方法。请参阅此处获取一些文档:http://site.mockito.org/mockito/docs/current/org/mockito/InOrder.html

此示例基于直接来自该文档的代码:

TASK [setup]     
<xyz.somehost.com> ESTABLISH CONNECTION FOR USER: TargetUser1 on PORT
22 TO xyz.somehost.com