Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestActorRef: Could not get the underlyingActor, says Nothing

I am trying to write my first ScalaTest for following 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)
  }
}

So, I do

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)
    }
  }
}

but what I see is

enter image description here

Why don't I get back the Runner Actor?

like image 671
daydreamer Avatar asked Nov 19 '25 06:11

daydreamer


1 Answers

Since Props is untyped it does not know which type of actor (in your case Runner) it will build. Consequently, the TestActorRef cannot infer the type either. This is why you need to explicitly state the type of the underlying actor when constructing your TestActorRef using

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

In case your actor did not require any parameters, this could even be shortened to

val runner = TestActorRef[Runner]

However, since Nothing is actually the base class of every scala type, the underlying actor is the same in either case. So if changing the TestActorRef definition were not possible it could also be casted to yield a Runner.

runner.underlyingActor.asInstanceOf[Runner]
like image 54
Michael Lang Avatar answered Nov 21 '25 19:11

Michael Lang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!