Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample showing basic usage of Akka TestKit and TestActorRef
package sample.akka.testkit
import akka.actor.ActorSystem
import akka.actor.Actor
import akka.testkit.{TestKit, TestActorRef}
import org.scalatest.matchers.MustMatchers
import org.scalatest.WordSpec
class ImplicitSenderTest extends TestKit(ActorSystem("testSystem"))
// Using the ImplicitSender trait will automatically set `testActor` as the sender
with ImplicitSender
with WordSpec
with MustMatchers {
"A simple actor" must {
"send back a result" in {
// Creation of the TestActorRef
val actorRef = TestActorRef[SimpleActor]
actorRef ! "akka"
// This method assert that the `testActor` has received a specific message
expectMsg("Hello akka")
}
}
}
package sample.akka.testkit
import akka.actor.ActorSystem
import akka.actor.Actor
import akka.testkit.{TestKit, TestActorRef}
import org.scalatest.matchers.MustMatchers
import org.scalatest.WordSpec
// Just a simple actor
class SimpleActor extends Actor {
// Sample actor internal state
var lastMsg: String = ""
def receive = {
case msg: String => {
// Storing the message in the internal state variable
lastMsg = msg
sender ! "Hello " + msg
}
}
}
class SimpleTest extends TestKit(ActorSystem("testSystem"))
with WordSpec
with MustMatchers {
"A simple actor" must {
// Creation of the TestActorRef
val actorRef = TestActorRef[SimpleActor]
"receive messages" in {
// This call is synchronous. The actor receive() method will be called in the current thread
actorRef ! "world"
// With actorRef.underlyingActor, we can access the SimpleActor instance created by Akka
actorRef.underlyingActor.lastMsg must equal("world")
}
}
}
@XOfSpades
Copy link

XOfSpades commented Oct 13, 2016

This leads to create state inside the actor just for testing purposes. I am new to Scala, but I would consider that as bad practice regarding the languages I used so far.

@rafaroca
Copy link

rafaroca commented Oct 18, 2016

The actor model defines actors to be completely isolated from each other. State should never leave actor boundaries. Within an actor however, state is fine. This example tests the correct storage of state within the actor so this looks fine to me.

@josecarlosbarros
Copy link

josecarlosbarros commented Nov 24, 2017

not compile here

libraryDependencies ++= Seq(
"org.apache.poi" % "poi" % "3.7",
"com.oracle.jdbc" % "driver" % "11.1.0.7",
"com.typesafe.akka" % "akka-actor_2.11" % "2.3.16",
"com.typesafe.akka" % "akka-testkit_2.11" % "2.3.16" % "test",
"org.scalatest" % "scalatest_2.11" % "3.0.4" % "test"
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment