使用TestKit进行测试时,期望在模拟actor上发送消息

时间:2016-03-04 15:40:09

标签: scala unit-testing akka

我正在尝试测试一个演员,这取决于另一个演员。在以下测试中ActorAMessageA发送给ActorB,并期望获得MessageB作为回报。

由于这是ActorB的单元测试,我正在嘲笑ActorA。我现在的问题是,我想确保ActorA得到MessageA,但是当我调用expectMsg时(请参阅注释行),整个自动驾驶仪似乎不再起作用了。

我在这里做错了吗?

class MyTest(_system: ActorSystem) extends TestKit(_system)
  with WordSpecLike
  with BeforeAndAfterAll {

  object Start
  object MessageA
  object MessageB

  def this() = this(ActorSystem("TestSpec"))

  override def afterAll() {
    system.shutdown()
  }

  // will later be mocked
  class ActorA extends Actor {
    def receive = {
      case MessageA => sender() ! MessageB
    }
  }

  class ActorB(actorA: ActorRef) extends Actor {
    def receive = {
      case Start => actorA ! MessageA
      case MessageB => println("Got MessageB")
    }
  }

  "" should {
    "work" in {
      val actorA = TestProbe()

      actorA.setAutoPilot(new AutoPilot {
        override def run(sender: ActorRef, msg: Any): AutoPilot = {
          msg match {
            case MessageA => sender ! MessageB
          }
          TestActor.KeepRunning
        }
      })

      // this will break the test
      //actorA.expectMsg(MessageA)

      val actor = system.actorOf(Props(new ActorB(actorA.ref)))
      actor ! Start
    }
  }

}

1 个答案:

答案 0 :(得分:0)

在向ActorB发送开始后,您应该期待MessageA。

  val actor = system.actorOf(Props(new ActorB(actorA.ref)))
  actor ! Start

  // this will not break the test
  actorA.expectMsg(MessageA)