3

我正在尝试写我的第一个ScalaTest以供关注Actor

object Runner {
  def props(race: Race) = Props(classOf[Runner], race)
}

class Runner(race: Race) extends Actor with ActorLogging {

  import context.dispatcher

  @throws[Exception](classOf[Exception])
  override def postRestart(reason: Throwable): Unit = context.parent ! RestartRunner

  override def receive: Receive = LoggingReceive {
    case Start => {
      log.debug("running...")
      for (i <- 1 to 3) {
        Thread.sleep(200)
      }
      throw new RuntimeException("MarathonRunner is tired")
    }

    case StartWithFuture =>
      log.debug("I am starting to run")
      race.start pipeTo self

    case Failure(throwable) => throw throwable

    case Stop =>
      log.debug("stopping runner")
      context.stop(self)
  }
}

所以,我愿意

import akka.actor.{Props, ActorSystem}
import akka.testkit.{TestActorRef, TestKit}
import org.scalatest._

class RunnerSpec extends TestKit(ActorSystem("test"))
with WordSpecLike
with MustMatchers {
  "A Runner Actor" must {
    val runner = TestActorRef(Props(new Runner(new Marathon)))
    "receive messages" in {
      runner ! Start
      runner.under <== says Nothing (see attachment)
    }
  }
}

但我看到的是

在此处输入图像描述

为什么我不拿回来Runner Actor

4

1 回答 1

3

由于Props是无类型的,它不知道Runner它将构建哪种类型的参与者(在您的情况下)。因此,TestActorRef也无法推断类型。这就是为什么你需要在构造你的TestActorRefusing时明确声明底层参与者的类型

val runner = TestActorRef[Runner](Props(new Runner(new Marathon)))

如果您的演员不需要任何参数,甚至可以缩短为

val runner = TestActorRef[Runner]

但是,由于Nothing实际上是每个 scala 类型的基类,因此在任何一种情况下底层的 actor 都是相同的。TestActorRef因此,如果无法更改定义,也可以将其强制转换为Runner.

runner.underlyingActor.asInstanceOf[Runner]
于 2015-06-02T08:02:47.533 回答