我正在尝试使用Mockito Framework测试应用程序。以下示例完美运行:
val dl = mock(classOf[DichListener])
val i = ArgumentCaptor.forClass(classOf[Int])
when(dl.test(i.capture())).thenCallRealMethod()
dl.test(666)
i.getValue shouldBe 666
然而,非常相似(但等待异步响应),下一个不会:
when(dl.echoReqCallback(c.capture(), m.capture())).thenCallRealMethod()
// Also not working:
// verify(dl).echoReqCallback(c.capture(), m.capture())
n2.sendEchoRequest("hello!")
Thread.sleep(1000)
println(m.getValue)
在echoReqCallback
之后调用 sendEchoRequest
,dl
是模拟对象。 echoReqCallback
作为对网络消息的响应运行,因此无法在行后立即调用:
n2.sendEchoRequest("hello!")
我尝试使用更长的sleep
时间,但结果始终相同:我的回调方法未被调用,因此m
变量没有获得任何值。
日志:
使用verify
:
> [info] org.mockito.exceptions.verification.WantedButNotInvoked:
> Wanted but not invoked:
> [info] dichListener.echoReqCallback(
> [info] <Capturing argument>,
> [info] <Capturing argument>
> [info] );
使用when
:
> [info] org.mockito.exceptions.base.MockitoException: No argument
> value was captured!
> [info] You might have forgotten to use argument.capture() in
> verify()...
> [info] ...or you used capture() in stubbing but stubbed method was not
> called. [info]
> Be aware that it is recommended to use capture() only with verify()
> [info]
> [info] Examples of correct argument capturing:
> [info] ArgumentCaptor<Person> argument =
> ArgumentCaptor.forClass(Person.class);
> [info] verify(mock).doSomething(argument.capture());
> [info] assertEquals("John", argument.getValue().getName());
修改
n1
已与n2
相关联。我想将n2
的Echo_Request发送到n1
并检查我在嘲讽dl
(n1
)后附加的听众(n1.listener = dl
)是否会触发{{ 1}}。逻辑正在测试代码之下。