Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save boseabhishek/d218c44d6f1c21ac419618412684b9b8 to your computer and use it in GitHub Desktop.
Save boseabhishek/d218c44d6f1c21ac419618412684b9b8 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")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment