如何模拟 Akka Actor 以对 class 进行单元测试?
How to mock an Akka Actor to Unit Test a class?
我有一个控制器 class,它控制发送到注入到控制器中的 Akka actor 的请求。
控制器代码:
class Controller(actor: ActorRef) {
def control(msg: String): Future[String] = {
actor.ask(msg)(Timeout(2 seconds)).mapTo[String]
}
}
我的演员代码是:
class ActorA extends Actor {
override def receive: Receive = {
case msg: String => sender ! msg
case msg: Int => sender ! msg.toString
case _ => "Invalid command!"
}
现在我需要模拟 ActorA 的行为以对 Controller 进行单元测试。有没有办法通过 Akka TestKit 做到这一点?
使用 TestProbe
. From the testing documentation:
val probe = TestProbe()
val future = probe.ref ? "hello"
probe.expectMsg(0 millis, "hello")
probe.reply("world")
assert(future.isCompleted && future.value == Some(Success("world")))
我有一个控制器 class,它控制发送到注入到控制器中的 Akka actor 的请求。
控制器代码:
class Controller(actor: ActorRef) {
def control(msg: String): Future[String] = {
actor.ask(msg)(Timeout(2 seconds)).mapTo[String]
}
}
我的演员代码是:
class ActorA extends Actor {
override def receive: Receive = {
case msg: String => sender ! msg
case msg: Int => sender ! msg.toString
case _ => "Invalid command!"
}
现在我需要模拟 ActorA 的行为以对 Controller 进行单元测试。有没有办法通过 Akka TestKit 做到这一点?
使用 TestProbe
. From the testing documentation:
val probe = TestProbe()
val future = probe.ref ? "hello"
probe.expectMsg(0 millis, "hello")
probe.reply("world")
assert(future.isCompleted && future.value == Some(Success("world")))