2

I want to test that preStart() creates right actors tree (Correct me, if I choose wrong place to create actors tree).

class Central extends Actor { 

  var summer : ActorRef = _

  override def preStart() = {
    val printerProps = Props[Printer]
    val printer = context.actorOf(printerProps, "printer")
    val summerProps = Props(new Summer(printer))
    summer = context.actorOf(summerProps, "summer")
  }

  override def receive = {
    case msg =>
  }
}

For full picture:

class Printer extends Actor {
  override def receive = {
    case msg => println(msg)
  }
}

class Summer(printer: ActorRef) extends Actor {
  override def receive = {
    case (x: Int, y: Int) =>
      printer ! x + y
  }
}

Any idea, how to make clear test of it?

This answer https://stackoverflow.com/a/18877040/1768378 is close for what I'am looking for. But I think that change code because a test reason is bad idea.

Maybe someone knows the better solution.

Community
  • 1
  • 1
vdshb
  • 1,949
  • 2
  • 28
  • 40

2 Answers2

1

IF you want to test just creation, you can also, from your test, get from the ActorSystem an ActorSelection containing all the children of your Central actor (central/*).

After that, send an Identify message (special akka message) to the whole selection and wait for the responses, checking whether they match. No need to inject code in your actors.

Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36
0

Snippet which based on answer of Diego Martinoia:

"The Central actor" should {
   "Create Summer" in {
      import scala.concurrent.duration._
      implicit val timeout = Timeout(3 seconds)

      val central = system.actorOf(Props[Central], "central")

      val summerSelection = system.actorSelection("user/central/summer")
      val summerRef = Await.result(summerSelection.resolveOne(), 3 seconds)
   }
}
vdshb
  • 1,949
  • 2
  • 28
  • 40
  • Note that, in case you DONT receive an answer within 3 seconds, that's not a guarantee that your actor has not been created. But probably you have some other issue if it responds so slowly. – Diego Martinoia Mar 08 '15 at 16:52
  • Yep, that's correct. And fault of the test is right signal. – vdshb Mar 10 '15 at 08:33