小编Sør*_*ren的帖子

ScalaTest 无法验证 Future 内的模拟函数调用

我尝试将 Scala 的 Future 与 ScalaTest 和 Mockito 一起使用,但通过一个非常简单的测试用例,我无法验证 Future 内模拟函数的任何调用。

import org.mockito.Mockito.{timeout, verify}
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class FutureTest extends FunSpec with MockitoSugar {
  it("future test") {
    val mockFunction = mock[() => Unit]

    Future {
      mockFunction()
    }

    verify(mockFunction, timeout(1000)).apply()
  }
}
Run Code Online (Sandbox Code Playgroud)

每次都会失败并出现以下错误:

Wanted but not invoked:
function0.apply$mcV$sp();
-> at test.FutureTest.$anonfun$new$1(FutureTest.scala:18)

However, there was exactly 1 interaction with this mock:
function0.apply();
-> at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:658)
Run Code Online (Sandbox Code Playgroud)

我已经测试过它在没有 Future 的情况下也能工作。

最令我惊讶的是,如果我也在 Future 块中包含 print 语句,它每次都会成功,如下所示:

Future {
  mockFunction()
  println("test") …
Run Code Online (Sandbox Code Playgroud)

scala future mockito scalatest

5
推荐指数
1
解决办法
1496
查看次数

标签 统计

future ×1

mockito ×1

scala ×1

scalatest ×1