使用Mockito在测试期间未调用异步回调

时间:2014-04-06 12:55:10

标签: java scala unit-testing timeout mockito

我正在尝试使用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之后调用

sendEchoRequestdl是模拟对象。 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并检查我在嘲讽dln1)后附加的听众(n1.listener = dl)是否会触发{{ 1}}。逻辑正在测试代码之下。

0 个答案:

没有答案