如何在Play Framework中使用Scala测试Akka Actor的典型示例

dnh*_*dnh 7 akka scalatest playframework specs2 playframework-2.0

在Play Framework中创建了一个Akka演员,我现在想测试一下.但是我马上遇到了一个问题:

  1. 当前的Play Scala Testing页面不包含测试Actors的任何内容,并且在所有示例中都使用Specs2
  2. 我在Play 2.2.1源代码测试或样本(也使用Specs2)中找不到演员测试示例.
  3. 阿卡演员测试页使用ScalaTest和阿卡系统设置似乎与由Play应用程序本身使用的不同.
  4. Akka actor测试确实讨论了使用Specs2的问题的解决方法,但没有提供这样一个测试的工作示例,当然也没有使用Play的内置测试夹具.

任何人都可以使用TestKit和Play的测试装置提供测试Akka演员的典型示例吗?

为了保持一致性,我更喜欢使用Specs2(坦率地说,为单个应用程序要求两个不同的测试框架似乎很奇怪)但是如果它与Play测试装置很好地集成,我将接受ScalaTest示例.

joh*_*ren 3

它确实没有什么特别的,你基本上只是有看起来像演员样本的测试,但使用了specs2测试语法。如果你想使用 akka 测试实用程序,你必须从你的 build.sbt 添加对它的显式依赖

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-testkit" % "2.2.0" % "test"
)   
Run Code Online (Sandbox Code Playgroud)

那么它没有什么特别的,除了你不能在测试类上继承 TestKit,因为Specification也是一个类并且有名称类。这是如何使用自定义范围来使用 TestKit 的示例:

import org.specs2.specification.Scope

class ActorSpec extends Specification {

  class Actors extends TestKit(ActorSystem("test")) with Scope

  "My actor" should {

     "do something" in new Actors {
       val actor = system.actorOf(Props[SomeActor])

       val probe = TestProbe()
       actor.tell("Ping", probe.ref)
       probe.expectMsg("Pong")
     }

    "do something else" in new Actors { new WithApplication {
      val actor = system.actorOf(Props[SomeActorThatDependsOnApplication])

      val probe = TestProbe()
      actor.tell("Ping", probe.ref)
      probe.expectMsg("Pong")
    }}

  }
}
Run Code Online (Sandbox Code Playgroud)