2015-11-21 34 views
1

有人能解釋爲什麼會失敗嗎?它是Akka文檔示例http://doc.akka.io/docs/akka/snapshot/scala/testing.html#Expecting_Log_Messages的一個直接副本。我錯過了什麼?Akka Actor使用Testkit EventListeners進行ScalaTest測試

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

保持每個測試,而不是壓倒一切的afterAll作品中的shutdown,但當然必要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) 
    } 
} 

我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" 
) 

回答

0

既然你做afterAll一個val它是在施工中進行評估並且在測試運行之前關閉參與者系統。將其更改爲方法(def),它將起作用。

+0

謝謝約翰 - 我想我一定在做一件傻事!真的很感謝你花時間回答 – Mark