如何测试 akka actor 的响应?

How to make tests on akka actors response?

我正在尝试了解 akka-Testkit",希望可以询问。

我发现一些教程和博客访问 TestActorRef 上底层 Actor 的 state- 或 lastMsg- 属性。但是,来自 "akka-testkit_2.11" % "2.4.10" 的 TestActorRef 没有这些属性。我查看了 akka 网站上的示例,也许我遗漏了一些东西,但他们展示了对 echo actor 的测试,但没有使用任何简单的 actor 实现。

所以,有人可以帮助我了解如何测试一个工作人员,如果 n % 3 == 0(示例中就是这种情况),该工作人员将以相同的数字响应。如果可能的话,我宁愿不使用 future 和 ask 模式,并且想测试 actor 将给出的响应(从 actor 的角度通过访问它的状态或类似的东西)。

class ProjectEulerScalaTestAkka extends TestKit(ActorSystem("testing")) with WordSpecLike with MustMatchers {

    "A simple actor" must {
        val actorRef = TestActorRef[Worker]
        "receive messages" in {
             actorRef ! 3
             actorRef.underlyingActor.state//must not equal("world")
        }
    }
}

相关:

目前我正在使用同步测试方法;

 import akka.actor.ActorSystem
 import akka.testkit.{TestActorRef, TestKit}
 import org.scalatest.Matchers
 import org.scalatest.WordSpecLike
 import akka.pattern.ask
 import scala.concurrent.Future
 import scala.concurrent.duration._
 import scala.util.Success

class ProjectEulerScalaTestAkka extends TestKit(ActorSystem("testing")) with WordSpecLike with Matchers {
      implicit val time = akka.util.Timeout(100 seconds)
      "A simple actor" must {
           val actorRef = TestActorRef[Worker]
           "receive messages" in {
               val f = (actorRef ? 3).asInstanceOf[Future[Int]]
               val reply = f.value.get
               reply should equal (Success(3))
           }
      }
}

我所做的是模拟我向其发送消息的 Actor 的接口,捕获消息并将成功消息发送回 testActor 引用。

具有捕获的消息负载的成功对象

case class SuccessWith(capturedMessage:Any = null)

您向其发送消息的模拟演员,反过来,returns对测试演员有一些价值

case class MockActor(requester: ActorRef) extends Actor {
  override def receive: Receive = {
    case i: Int => {
      requester ! i
    }
  }
}

设置您想要进行单元测试的 actor

val actorRef = system.actorOf(Props(new YourActor(args)))

然后是你的测试

  "A simple actor" must {
       "receive messages" in {
           val f = actorRef ! 3
           expectMsg(Success(3))
       }
  }
}