Mockito:等待与参数匹配的调用 [英] Mockito: wait for an invocation that matches arguments

查看:411
本文介绍了Mockito:等待与参数匹配的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个selenium测试并使用mockito验证服务器行为。具体来说,当单击一个按钮时,我想确保页面控制器调用我所模拟的依赖项上的特定方法。

I'm writing a selenium test and verifying the server behavior with mockito. Specifically, when a button is clicked, I want to make sure the page controller calls a particular method on a dependency which I've mocked.

因为它是一个硒测试,我需要等待在另一个线程中调用mock,所以我使用mockito timeout。

Because it is a selenium test, I need to wait for the mock to be invoked in another thread, so I'm using mockito timeout.

verify(myMock, timeout(5000).times(1)).myMethod("expectedArg");

我遇到的麻烦是多次调用myMethod而不是等待与预期参数匹配的调用,timeout仅等待第一次调用。
如果我使用Thread.sleep(50000)而不是超时(50000),它按预期工作......但这很脏,所以我希望避免它。

The trouble that I'm having is that myMethod is called many times... rather than waiting for an invocation that matches the expected arguments, timeout only waits for the first invocation. If I use Thread.sleep(50000) rather than timeout(50000), it works as expected... but that's dirty so I'm hoping to avoid it.

如何等待使用预期输入调用myMethod?

How do I wait for myMethod to be invoked with the expected input?

推荐答案

这不是一个超级干净的解决方案但你可以这样做( XX 这里是假设的返回类型):

This is not a super clean solution but you can do this (XX is the supposed return type here):

final CountDownLatch latch = new CountDownLatch(1);

doReturn(new Answer<XX>()
    {
        @Override
        public XX answer(InvocationOnMock invocation)
        {
            latch.countDown();
            return someInstanceOfXX;
        }
    }
).when(myMock).myMethod("expectedArg");

然后,为了测试方法是否被调用,请执行:

Then, to test if the method is called, do:

try {
    assertTrue(latch.await(5L, TimeUnit.SECONDS));
} catch (InterruptedException e) {
    // Urgh... Failed. Deal with it and:
    Thread.currentThread.interrupt();
}

这篇关于Mockito:等待与参数匹配的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆