Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonical Example of how to test Akka Actor using Scala in Play Framework

Having created an Akka actor in Play Framework, I now want to test it. However I immediately hit a problem:

  1. The current Play Scala Testing page contains nothing about testing Actors and uses Specs2 for all examples
  2. I could find no actor test examples in the Play 2.2.1 source tests, or in the samples (which also use Specs2).
  3. The Akka actor test page uses ScalaTest, and the Akka system setup appears different from that used by the Play application itself.
  4. The Akka actor test does discuss workarounds for problems using Specs2, but without providing a worked example of such a test, and certainly not one using Play's built-in test fixtures.

Can anyone provide a canonical example of testing an Akka actor using TestKit and Play's test fixtures?

For consistency's sake I would prefer it to use Specs2 (frankly, it seems bizarre to require two different testing frameworks for a single app) however I will accept a ScalaTest example if it integrates well with the Play test fixtures.

like image 459
dnh Avatar asked Jan 19 '14 15:01

dnh


1 Answers

There is really nothing special to it, you basically just have tests that looks like the actor samples but using the specs2 test syntax instead. If you want to use the akka test utilities you will have to add an explicit dependency on it from your build.sbt

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-testkit" % "2.2.0" % "test"
)   

Then there is nothing special to it, except that you cannot inherit TestKit on the test class since Specification also is a class and there are name classes. This is an example of how you could use a custom Scope for using TestKit:

import org.specs2.specification.Scope

class ActorSpec extends Specification {

  class Actors extends TestKit(ActorSystem("test")) with Scope

  "My actor" should {

     "do something" in new Actors {
       val actor = system.actorOf(Props[SomeActor])

       val probe = TestProbe()
       actor.tell("Ping", probe.ref)
       probe.expectMsg("Pong")
     }

    "do something else" in new Actors { new WithApplication {
      val actor = system.actorOf(Props[SomeActorThatDependsOnApplication])

      val probe = TestProbe()
      actor.tell("Ping", probe.ref)
      probe.expectMsg("Pong")
    }}

  }
}
like image 127
johanandren Avatar answered Nov 16 '22 09:11

johanandren