scala - 为什么当我执行 Await.result 时我的 Scala 异步测试永远不会完成?

标签 scala asynchronous future scalatest

我创建了一个简单的测试场景来展示这一点:

class Test extends AsyncFunSuite {

  test("async test") {
    val f = Future {
      val thread = new Thread {
        override def run(): Unit = {
          println("OKAYY")
        }
      }
      thread.start()
    }

    Await.result(f, Duration.Inf)
    Future {
      assert(true)
    }
  }

}

执行此操作时,测试将永远运行并且永远不会完成。

最佳答案

您将在 ScalaTest 中的所有异步测试(AsyncFeatureSpec、AsyncFlatSpec、AsyncFreeSpec、AsyncFunSpec、AsyncFunSuite、AsyncWordSpec)中看到相同的行为。

这是因为ScalaTest中默认的执行上下文是串行执行上下文。您可以在这里阅读更多相关信息:https://www.scalatest.org/user_guide/async_testing .我总结了以下要点。

Using ScalaTest's serial execution context on the JVM will ensure the same thread that produced the Future[Assertion] returned from a test body is also used to execute any tasks given to the execution context while executing the test body—and that thread will not be allowed to do anything else until the test completes.

This thread confinement strategy does mean, however, that when you are using the default execution context on the JVM, you must be sure to never block in the test body waiting for a task to be completed by the execution context. If you block, your test will never complete.

解决方案 1:覆盖执行上下文

implicit override def executionContext = scala.concurrent.ExecutionContext.Implicits.global

解决方案 2:链接

class Test extends AsyncFunSuite {

  test("async test") {
    val f = Future {
      val thread = new Thread {
        override def run(): Unit = {
          println("OKAYY")
        }
      }
      thread.start()
    }

    f.map { _ =>
      assert(true)
    }
  }

}

关于scala - 为什么当我执行 Await.result 时我的 Scala 异步测试永远不会完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62242989/

相关文章:

multithreading - NCompBus和WCF间歇性地无法完成TaskCompletionSource

rust - 如何在 future 链中使用包含在结果类型中的套接字?

java - 监听某些变化并将其更新到数据库

java - 如果任何包占用大量时间,则使线程超时

Android长轮询-执行服务超时

scala - 使用 Spark Streaming 从 http 创建分析

scala - 向 Symbol 添加更新方法时遇到问题

scala - 如何使用Play Framework读取测试代码中的资源?

scala - 如何将 spark sql 输出收集到文件中?

arrays - 从 firebase 存储中检索图像以显示在 tableView 上 (Swift)