How to wait for Akka actor to start during tests?

旧巷老猫 提交于 2020-03-06 04:59:08

问题


I have a test that needs to make an assertion on something that happens during an actor's preStart(), but I haven't figured out how to wait until that happens, and sometimes it doesn't happen before the assertion is made (and sometimes it does). I have tried this:

EventFilter.debug(start = "started", occurrences = 1).assertDone(10.seconds)

but I get an error message when using it:

java.lang.AssertionError: assertion failed: 1 messages outstanding on DebugFilter(None,Left(started),false)

回答1:


You could place the creation of the actor inside an intercept block:

import akka.actor._
import akka.testkit.EventFilter
import com.typesafe.config.ConfigFactory

class MyActor extends Actor with ActorLogging {
  override def preStart(): Unit = {
    log.debug("started MyActor...")
  }

  def receive = {
    case m => log.debug(s"Received this message: $m")
  }
}

object MyActor {
  def props() = Props[MyActor]
}

object EventFilterTest extends App {
  implicit val system = ActorSystem("testsystem", ConfigFactory.parseString("""
    akka.loggers = ["akka.testkit.TestEventListener"]
    akka.loglevel = "DEBUG"
  """))

  EventFilter.debug(start = "started", occurrences = 1) intercept {
    val myActor = system.actorOf(MyActor.props)
    myActor ! "cows"
  }
}

Running the above code produces the following output:

[DEBUG] [...] [run-main-0] [EventStream(akka://testsystem)] logger log1-TestEventListener started
[DEBUG] [...] [run-main-0] [EventStream(akka://testsystem)] Default Loggers started
[DEBUG] [...] [testsystem-akka.actor.default-dispatcher-5] [akka://testsystem/user/$a] Received this message: cows

The intercept "catches" the debug statement in the actor's preStart hook.



来源:https://stackoverflow.com/questions/46354732/how-to-wait-for-akka-actor-to-start-during-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!