【问题标题】:Canonical Example of how to test Akka Actor using Scala in Play Framework如何在 Play Framework 中使用 Scala 测试 Akka Actor 的典型示例
【发布时间】:2023-03-31 01:02:01
【问题描述】:

在 Play Framework 中创建了一个 Akka actor,我现在想对其进行测试。但是我立即遇到了一个问题:

  1. 当前的Play Scala Testing 页面不包含任何关于测试 Actor 的内容,并且所有示例都使用 Specs2
  2. 我在 Play 2.2.1 源测试或示例(也使用 Specs2)中找不到任何参与者测试示例。
  3. Akka actor test page 使用 ScalaTest,Akka 系统设置看起来与 Play 应用程序本身使用的不同。
  4. Akka actor 测试确实讨论了使用 Specs2 的问题的解决方法,但没有提供此类测试的有效示例,当然也没有使用 Play 的内置测试装置。

谁能提供一个使用 TestKit 和 Play 的测试装置测试 Akka Actor 的规范示例?

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

【问题讨论】:

标签: playframework playframework-2.0 akka scalatest specs2


【解决方案1】:

实际上并没有什么特别之处,你基本上只是有看起来像演员样本但使用 specs2 测试语法的测试。如果你想使用 akka 测试工具,你必须在你的 build.sbt 中添加一个明确的依赖

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-testkit" % "2.2.0" % "test"
)   

那么它没有什么特别的,除了你不能在测试类上继承TestKit,因为规范也是一个类并且有名称类。这是一个如何使用自定义 Scope 来使用 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")
    }}

  }
}

【讨论】:

  • 谢谢。目前它没有为我编译,给出could not find implicit value for evidence parameter of type org.specs2.execute.AsResult 错误。明天早上我会努力追上去的。
  • 好的,是的。这是一个导入问题:Scope 应该是 org.specs2.specification.Scope 而不是 akka.actor.Scope
  • in new Actors 本身(没有new WithApplication)给出There is no started application akka.actor.ActorInitializationException: exception during creation 是否有任何场景可以在不启动应用程序的情况下测试参与者? (例如,第一次测试是一个有效的场景吗?)在使用 WithApplication 时也能完美运行,顺便说一句。
  • 这取决于你在你的actor中做了什么,如果你避免接触任何依赖于应用程序的东西,actor可以独立测试(你可以通过从不导入play.api.Play.current来确保这一点在演员范围内)。实现这一点的一种方法是 DI - 为道具工厂方法提供任何设置,并且仅使用您在应用程序中创建演员的播放配置。
  • 我明白了。所以我应该在应用程序本身(使用 Play 应用程序配置)中使用 Play 的隐式版本(例如 ExecutionContext),但是如果我使用 Akka 隐式,可以单独测试 Actor?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 2017-08-25
  • 2013-11-27
  • 2019-02-12
  • 2012-05-20
  • 1970-01-01
相关资源
最近更新 更多