如何结合 WithApplication(Loader) 和 ExecutionEnv

How to combine WithApplication(Loader) and ExecutionEnv

我正在为使用 Scala 和 Play 框架的项目中返回 futures 的方法编写 Specs2 测试。 Documentation and answers to 推荐使用await修饰符,需要添加implicit ExecutionEnv。一个最小的工作示例(改编自上述答案之一):

class FutureSpec extends mutable.Specification {
  "Even in future one" should {
    "be greater than zero" in { implicit ee: ExecutionEnv =>
      Future(1) must be_>(0).await
    }
  }
}

但是我的一些测试需要 WithApplicationLoader。如果我将它添加到示例中,它不会编译:

class FutureSpec extends mutable.Specification {
  "Even in future one" should {
    "be greater than zero" in new WithApplicationLoader { implicit ee: ExecutionEnv =>
      Future(1) must be_>(0).await
    }
  }
}

WithApplication 而不是 WithApplicationLoader 具有完全相同的效果(预期)。

是否可以将 WithApplicationLoader 与隐式 ExecutionEnv 一起使用?

不幸的是,文档中描述的第二个选项——将 ExecutionEnv 移动到 class 构造函数而不是特定方法——不可用。本规格:

class FutureSpec(implicit ee: ExecutionEnv) extends mutable.Specification {
  "Even in future one" should {
    "be greater than zero" in new WithApplicationLoader {
      Future(1) must be_>(0).await
    }
  }
}

有效,但被IntelliJ Idea忽略(我可以单独运行这样的规范,但是配置运行ning项目中的所有测试都不执行)

您随时可以这样做

class TestSpec extends mutable.Specification {
  "test1" >> { implicit ee: ExecutionEnv =>
    new WithApplicationLoader {
      ok
    }
  }
}

这适用于 IntelliJ 2016.1.3:

import play.api.test.{PlaySpecification, WithApplication}
import org.specs2.concurrent.ExecutionEnv
import scala.concurrent.Future

class FutureSpec extends PlaySpecification {
  implicit val ee = ExecutionEnv.fromGlobalExecutionContext
//  // or this:
//  implicit val ee = ExecutionEnv.fromExecutionContext(play.api.libs.concurrent.Execution.Implicits.defaultContext)

  "Even in future one" should {
    "be greater than zero" in new WithApplication {
      Future(1) must be_>(0).await
    }
  }
}

这是我的 build.sbt:

name := "throwaway"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "org.specs2" %% "specs2-core" % "3.8.5.1" % "test"

libraryDependencies += "com.typesafe.play" %% "play" % "2.5.9" % "test"

libraryDependencies += "com.typesafe.play" %% "play-specs2" % "2.5.9" % "test"

libraryDependencies += "com.typesafe.play" %% "play-test" % "2.5.9" % "test"