How to mock an Akka Actor to Unit Test a class?

限于喜欢 提交于 2019-12-05 01:06:24

问题


I have a Controller class which controls the requests sent to a Akka actor which is injected in to the controller.

Controller's code:

class Controller(actor: ActorRef) {
  def control(msg: String): Future[String] = {
    actor.ask(msg)(Timeout(2 seconds)).mapTo[String]
  }
}

And my Actor's code is:

class ActorA extends Actor {
  override def receive: Receive = {
    case msg: String => sender ! msg
    case msg: Int => sender ! msg.toString
    case _ => "Invalid command!"
}

Now I need to mock ActorA's behaviour to unit test Controller. Is there a way to do so via Akka TestKit ?


回答1:


Use a 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")))


来源:https://stackoverflow.com/questions/34265013/how-to-mock-an-akka-actor-to-unit-test-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!