This can be tested using the Akka testkit along with Scala Test.
Take the following very simple example. We have an Actor called Server which should accept Startup messages and respond with a Ready message when it is ready for clients to send additional messages.
We can start with a noddy implementation that does nothing:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package batey.akka.testing.backtosender | |
import akka.actor.Actor | |
class Server extends Actor { | |
def receive: Actor.Receive = { | |
case msg @ _ => { | |
println("I should really send something back!") | |
} | |
} | |
} | |
case object Messages { | |
case object Startup | |
case object Ready | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package batey.akka.testing.backtosender | |
import akka.testkit.{ImplicitSender, TestKit} | |
import akka.actor.{Props, ActorSystem} | |
import org.scalatest.FunSuiteLike | |
class ServerTest extends TestKit(ActorSystem("TestSystem")) with FunSuiteLike with ImplicitSender { | |
test("Should send back Ready message when Startup message is received") { | |
val actorRef = system.actorOf(Props[Server]) | |
actorRef ! Messages.Startup | |
expectMsg(Messages.Ready) | |
} | |
} |
assertion failed: timeout (3 seconds) during expectMsg while waiting for Ready
As you can probably guess TestKit waited for 3 seconds for a Ready message to be sent back.
To fix the test we add the the following to the Server Actor implementation:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package batey.akka.testing.backtosender | |
import akka.actor.Actor | |
import batey.akka.testing.backtosender.Messages.{Ready, Startup} | |
class Server extends Actor { | |
def receive: Actor.Receive = { | |
case Startup => { | |
sender ! Ready | |
} | |
case msg @ _ => { | |
println("I should really send something back!") | |
} | |
} | |
} | |
case object Messages { | |
case object Startup | |
case object Ready | |
} |
No comments:
Post a Comment