scala - 如何测试向另一个 Actor 发送消息的 Akka Actor ?

标签 scala akka scalatest akka-testkit

我将 ScalaTest 与 Akka TestKit 结合使用,为我编码的角色编写单元和集成测试,以便简单地向另一个角色发送消息,而不会改变任何内部状态。以这个为例:

class MyActor extends Actor {
  val anotherActor = context.actorOf(Props[AnotherActor])
  def receive: Receive = {
    case MyMessage => anotherActor ! AnotherMessage
  }
}

我想编写一个测试来确认 anotherActor已处理 AnotherMessage由于 MyActor加工MyMessage .经典的例子是使用 TestActorRef获取底层参与者并检查一些在收到消息时应该受到影响的内部状态,如下所示:
val testActorRef = TestActorRef(new MyActor)
"MyActor" should "change some internal state when it receives MyMessage" in {
  testActorRef ! MyMessage
  testActorRef.underlyingActor.someState shouldBe "altered"
}

但就我而言,我不在乎这种状态。事实上,我想避免持有任何这样的状态。 TestProbe也不是我想要的,因为您仍然需要注册 TestProbe.ref与被测 Actor 。在大多数情况下,我已经查看了 Akka 测试文档 ( http://doc.akka.io/docs/akka/snapshot/scala/testing.html ) 中的所有示例,但没有找到任何合适的示例。

最佳答案

可能有几种方法可以做到这一点,当我们有类似的测试时,我将向您展示一种有效的方法。我还是觉得TestActorRef , TestKitTestProbe是要走的路。考虑以下结构:

case object MyMessage
case object AnotherMessage

class MyActor extends Actor {
  val anotherActor = createAnother
  def receive: Receive = {
    case MyMessage => anotherActor ! AnotherMessage
  }

  def createAnother = context.actorOf(Props[AnotherActor])
}

class AnotherActor extends Actor{
  def receive = {
    case _ =>
  }
}

问题是您有一个创建子actor 的actor 实例,并且作为测试的一部分,您需要确保该child 收到消息,即使您在测试中对创建该子actor 没有任何控制权。当我们遇到这种情况时,我们会做一些简单的事情,如下所示(使用 specs2 完成,但应该能够在 ScalaTest 中创建类似的东西):
import akka.actor._
import akka.testkit._
import org.specs2.mutable.SpecificationLike
import org.specs2.runner.JUnitRunner
import org.junit.runner.RunWith

class MessageSendingSpec extends TestKit(ActorSystem("test")) with SpecificationLike{

  val probe = TestProbe()
  val myActor = TestActorRef(new MyActor{
    override def createAnother = probe.ref
  })


  "Sending MyMessage to an instance of MyActor" should{
    "pass AnotherMessage to the child AnotherActor" in {
      myActor ! MyMessage
      probe.expectMsg(AnotherMessage)
      success
    }
  }
}

关键是,在创建要测试的角色时,我会覆盖创建子角色的方法以提供我的探针。它很粗糙,但也简单有效。

关于scala - 如何测试向另一个 Actor 发送消息的 Akka Actor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270024/

相关文章:

Akka Actor : Path lookup efficiency

ScalaTest、Mockito、Guice 和 PartialMocking

Java Spring 作为基于 Akka 的 REST HTTP 调用的客户端

scala - 运行 Akka 微内核时获取命令行参数?

arrays - 是否可以使用 assertResult 在 ScalaTest 中检查数组是否相等

scala - 当 akka Actor 在测试线程之外抛出异常时,scalatest 失败

java - Scala - 如何将回调传递给方法

scala - 具有非实例变量助手的构造函数?

Scala 对象作为字段

Scala:检查2个变量是否属于同一类型