java 参数匹配,java – Mockito:等待与参数匹配的调用

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

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

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

我遇到的麻烦是myMethod被多次调用…而不是等待与预期参数匹配的调用,超时只等待第一次调用.

如果我使用Thread.sleep(50000)而不是超时(50000),它会按预期工作……但这很脏,所以我希望避免它.

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

解决方法:

如果您能够设置一定数量的预期调用,可以使用ArgumentCaptor完成:

import static org.hamcrest.CoreMatchers.hasItem;

@Captor ArgumentCaptor arg;

@Before

public void setUp() throws Exception {

// init the @Captor

initMocks(this);

}

@Test

public void testWithTimeoutCallOrderDoesntMatter() throws Exception {

// there must be exactly 99 calls

verify(myMock, timeout(5000).times(99)).myMethod(arg.capture());

assertThat(arg.getAllValues(), hasItem("expectedArg"));

}

另一种方法是指定要验证的所有预期值,但这些值需要按照它们被调用的确切顺序提供.与上述解决方案的不同之处在于,即使使用一些未经验证的参数另外调用mock,这也不会失败.换句话说,无需知道总调用次数.代码示例:

@Test

public void testWithTimeoutFollowingCallsDoNotMatter() throws Exception {

// the order until expected arg is specific

verify(callback, timeout(5000)).call("firstExpectedArg");

verify(callback, timeout(5000)).call("expectedArg");

// no need to tell more, if additional calls come after the expected arg

// verify(callback, timeout(5000)).call("randomArg");

}

标签:java,selenium,asynchronous,testing,mockito

来源: https://codeday.me/bug/20191007/1866397.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值