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

Java 在使用Mockito进行测试期间未调用异步回调,java,scala,unit-testing,timeout,mockito,Java,Scala,Unit Testing,Timeout,Mockito,我正在尝试使用Mockito框架测试应用程序。以下示例非常有效: val dl = mock(classOf[DichListener]) val i = ArgumentCaptor.forClass(classOf[Int]) when(dl.test(i.capture())).thenCallRealMethod() dl.test(666) i.getValue shouldBe 666 但是,非常类似,但正在等待异步响应,下一个不会:

我正在尝试使用Mockito框架测试应用程序。以下示例非常有效:

    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)
在sendEchoRequest之后调用echoReqCallback,dl是模拟对象。echoReqCallback是作为对网络消息的响应运行的,因此它无法在第行之后立即调用:

n2.sendEchoRequest("hello!")
我尝试使用更长的睡眠时间,但结果总是一样的:我的回调方法没有被调用,因此m变量没有得到任何值

日志: 使用验证:

编辑:
n1连接到n2。我想将Echo_请求从n2发送到n1,并检查我在模拟n1 n1.listener=dl后附加的侦听器dl是否会触发echoReqCallback。逻辑在测试代码下运行。

您没有为我们提供足够的信息来诊断您的问题。但是看起来dl是您正在测试的对象。如果是这样,你为什么要嘲笑它?还是我误解了你在做什么?没错。我相信我需要先模拟对象,然后才能在when方法中使用它。dl运行echoReqCallback方法当然,我可以看到调试消息,但是捕获的变量是空的,m和c。如果您所做的只是让它调用真正的方法,那么您不需要when。你模拟一个对象是因为你希望它的行为不同于未被模拟的对象。但这会使你的测试无效。测试一个通过模拟改变了其行为的对象通常是没有意义的。简言之,不要模拟您试图测试的对象。实际上,我想创建一些回调,而不是虚拟睡眠来测试网络连接。那么哪个类有回调方法呢?
> [info]   org.mockito.exceptions.verification.WantedButNotInvoked:
> Wanted but not invoked:                                            
> [info] dichListener.echoReqCallback(                                  
> [info]     <Capturing argument>,                                      
> [info]     <Capturing argument>                                       
> [info] );
> [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());