daydreamer
daydreamer

Reputation: 91949

Actor not catching exception in Test even if thrown

My Actor looks like

object LogProcessorActor {
  def props(f: () => Unit): Props = Props(new LogProcessorActor(f))
}

class LogProcessorActor(f: () => Unit) extends Actor with ActorLogging {
  def receive = LoggingReceive {
    case StartLogReaderDisruptor => f()
      sender ! StartedLogReaderDisruptor
  }
}

and my test looks like

  it must "fail with method throws exception" in {
    val f: () => Unit = () => 2/0
    val logProcessorRef = TestActorRef[LogProcessorActor](LogProcessorActor.props(f), name = "logProcessorSad")
    intercept[ArithmeticException] {
      logProcessorRef ! StartLogReaderDisruptor
    }
  }

I see in logs that the exception is thrown

[DEBUG] [06/02/2015 19:25:44.598] [ScalaTest-run] [EventStream(akka://logProcessorActorSystem)] logger log1-Slf4jLogger started
[DEBUG] [06/02/2015 19:25:44.599] [ScalaTest-run] [EventStream(akka://logProcessorActorSystem)] Default Loggers started
02 Jun 2015 19:25:44,601 [DEBUG] [logProcessorActorSystem-akka.actor.default-dispatcher-3] akka.event.EventStream| logger log1-Slf4jLogger started
02 Jun 2015 19:25:44,603 [DEBUG] [logProcessorActorSystem-akka.actor.default-dispatcher-3] akka.event.EventStream| Default Loggers started02 Jun 2015 19:25:44,782 [ERROR] [logProcessorActorSystem-akka.actor.default-dispatcher-3] akka.actor.OneForOneStrategy| / by zero
java.lang.ArithmeticException: / by zero
    at com.shn.lp.LogProcessorActorSpec$$anonfun$3$$anonfun$4.apply$mcV$sp(LogProcessorActorSpec.scala:18)
    at com.shn.lp.LogProcessorActor$$anonfun$receive$1.applyOrElse(LogProcessorActor.scala:16)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:467)
    at com.shn.lp.LogProcessorActor.aroundReceive(LogProcessorActor.scala:14)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)

But still my test fails as

Expected exception java.lang.ArithmeticException to be thrown, but no exception was thrown.
ScalaTestFailureLocation: com.shn.lp.LogProcessorActorSpec$$anonfun$3 at (LogProcessorActorSpec.scala:20)
org.scalatest.exceptions.TestFailedException: Expected exception java.lang.ArithmeticException to be thrown, but no exception was thrown.

I even tried the strategy mentioned in docs, but I still get the same result.

What am I doing incorrect?

Upvotes: 0

Views: 734

Answers (1)

Ryan
Ryan

Reputation: 7247

An uncaught exception thrown in an actor's receive block will not be handled by the sender. It will be handled according to the actor's supervision hierarchy. The parent actor will deal with the child according to its supervisor strategy.

This is covered in the Actors and exceptions section of the documentation: http://doc.akka.io/docs/akka/2.3.11/scala/actors.html#Actors_and_exceptions

Upvotes: 3

Related Questions