Skip to content

Instantly share code, notes, and snippets.

@mguillermin
Last active February 5, 2021 07:47
Show Gist options
  • Save mguillermin/5788415 to your computer and use it in GitHub Desktop.
Save mguillermin/5788415 to your computer and use it in GitHub Desktop.
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

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

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.

Copy link

ghost 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