【问题标题】:Testing actor crash using TestActorRef使用 TestActorRef 测试actor崩溃
【发布时间】:2017-03-23 12:25:07
【问题描述】:

我是演员新手,我正在学习如何使用TestActorRef 测试演员

我的演员代码:

package actors

import actors.GreetingActor.Hi
import akka.actor.Actor

object GreetingActor {
  case class Hi()
}

class GreetingActor extends Actor {

  var greeting = ""

  override def receive: Receive = {
    case Hi() =>
      greeting = "Hi"
    case _ =>
      throw new IllegalArgumentException("not supported message")
  }

  override def postRestart(reason: Throwable) = {
    println(s"actor is restarted because of ${reason.getMessage}")
  }
}

我确信这段代码中的一切都按我的意愿工作,但我无法在测试中显示它。尤其是我无法展示最重要的事情之一,我的演员坠毁了。测试非常简单且明显,我发送的消息不是Hi(),并且应该以某种方式跟踪那个演员与IllegalArgumentException 一起崩溃。我当前的测试代码:

package actors

import actors.GreetingActor.Hi
import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit}
import org.scalatest.{MustMatchers, WordSpecLike}

class GreetingActorTest extends TestKit(ActorSystem("testsystem")) with WordSpecLike
  with MustMatchers with StopSystemAfterAll {

  "A Hello Actor" must {
    "change state when it receives a message, single threaded" in {
      val greetingActor = TestActorRef[GreetingActor]
      greetingActor ! Hi()
      greetingActor.underlyingActor.greeting mustBe "Hi"
    }
    "throw exception when it received unknown message, single threaded" in {
      val greetingActor = TestActorRef[GreetingActor]
      greetingActor ! "hi"
      //some code that checks that actor crashed
    }
  }

}

问题是如何在测试中跟踪我的演员使用TestActorRef 崩溃的情况?感谢任何帮助。

【问题讨论】:

    标签: scala testing akka actor


    【解决方案1】:

    将您的测试更改为以下内容:

    "throw exception when it received unknown message, single threaded" in {
      assertThrows[IllegalArgumentException] {
          val greetingActor = TestActorRef[GreetingActor]
    
          greetingActor.receive("hi")
      }
    }
    

    根据演员文档,您需要使用接收,这样异常就不会被吞没:

    http://doc.akka.io/docs/akka/current/scala/testing.html#The_Way_In-Between__Expecting_Exceptions

    【讨论】:

    • 我太草率了,我应该仔细阅读文档。谢谢。我猜有人会google它,所以我不会删除它。
    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 2012-05-20
    • 1970-01-01
    • 2015-08-14
    • 2015-07-24
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多