1
votes

Can someone please explain why this fails? It is a straight copy of the Akka docs example http://doc.akka.io/docs/akka/snapshot/scala/testing.html#Expecting_Log_Messages into a spec. What am I missing?

import akka.actor.{ActorSystem, Props, ActorKilledException, Kill}
import akka.testkit.{ TestKit, EventFilter}
import org.scalatest.{FlatSpecLike, BeforeAndAfterAll}
import com.typesafe.config.ConfigFactory

class MySpec() 
  extends TestKit(ActorSystem("testsystem", ConfigFactory.parseString(
    """akka.loggers = ["akka.testkit.TestEventListener"]""")))
  with FlatSpecLike with BeforeAndAfterAll {

  override val afterAll = shutdown(system)
  //afterAll executes without waiting for the EventFilter.intercept, resulting in 
  //  java.lang.IllegalStateException: cannot create children while terminating or terminated
  //  at akka.actor.dungeon.Children$class.makeChild(Children.scala:213)...

  behavior of "MyActor"

  it should "throw an exception when killed" in {
    val actor = system.actorOf(Props.empty)
    EventFilter[ActorKilledException](occurrences = 1) intercept {
      actor ! Kill
    }
  } 
}

Keeping the shutdown within each test instead of overriding afterAll works, but of course necessitates OneInstancePerTest

it should "throw an exception when killed" in {
  try {
    val actor = system.actorOf(Props.empty)
    EventFilter[ActorKilledException](occurrences = 1) intercept {
      actor ! Kill
    }
  } finally {
    shutdown(system)
  }
} 

My build.sbt

lazy val root = (project in file(".")).
  settings(
    name := "TestkitAfterall",
    version := "1.0",
    scalaVersion := "2.11.7"
  )

lazy val akkaVersion = "2.4.0"

libraryDependencies ++=  Seq(
  "com.typesafe.akka" %% "akka-actor" % akkaVersion,
  "com.typesafe.akka" %% "akka-testkit" % akkaVersion,
  "org.scalatest" % "scalatest_2.11" % "2.2.5"
)
1

1 Answers

0
votes

Since you made afterAll a val it is evaluated on construction and the actor system is shutdown before the tests are run. Change it to a method (def) and it will work.