模拟角色及其在单元测试中的响应。

问题描述 投票:1回答:1

我有一个在actor内部被启动的actor,我想模拟actorB,使消息actorB ? GetDataForProcessing(value)不会被发送到actorB,我可以测试ActorExp的单元功能。

我的actor是。

class ActorExp(a: ARepo) extends Actor{

  lazy val actorB = context.system.actorSelection("user/ActorB")

  def receive: Receive = {

    case m @ GetData(value) =>
          sender() ! getData(value)
  }

  def getData(value:String) = {
    val res = actorB ? GetDataForProcessing(value)
    res map {
           ...
    }
  }
}

class ActorB(repoB: BRepo) extends Actor{...}

我想写的测试是:

class ActorExpSpecSpec
        extends TestKit(ActorSystem("ActorExpSpecSpec"))
        with WordSpecLike
        with Matchers
        with JsonSupport
        with MockitoSugar
        with BeforeAndAfterAll
        with ImplicitSender {
  override def afterAll: Unit = TestKit.shutdownActorSystem(system)

  implicit val futureDuration: FiniteDuration = 60.seconds
  implicit val timeout: Timeout               = 10.seconds
  val mockedRepoA                       = mock[ARepo]

  val actorA: ActorRef                  = TestActorRef(ActorExp.props(mockedRepoA))

  "ActorExpSpecSpec" should {
    "be able to data" in {

      val action = (actorA ? GetData("value")).mapTo[Seq[String]]
      val result = Await.result(action, 10.seconds)
      result should equal("yes")
    } 
  }
}

现在我得到了一个请求超时的异常,因为 actorB 没有被初始化,因为它需要某些参数,我不想测试 actorB. 在上面所说的情况下,有什么办法可以让我模拟出 actorB 及其信息 actorB ? GetDataForProcessing(value)?

scala mocking akka scalatest akka-testkit
1个回答
1
投票

添加额外的构造函数参数到 ActorExp 定义了角色选择路径 user/ActorB 并在您的测试表格中提供 TestProbe().ref.path

下面是一些简化的例子如何做。

  class ParentActor(actorPath: String) extends Actor {

    private val selected = context.system.actorSelection(actorPath)

    override def receive: Receive = {
      case msg: String =>
        val replyTo = sender()
        //some irrelevant logic to test
        (selected ? msg).mapTo[String].onComplete {
          case Success(v)  => replyTo ! v
          case Failure(ex) => throw ex
        }
    }
  }

现在,你可以提供一个 TestProbe 在测试时,像这样把路径输入到你的actor中。

val testProbe = TestProbe()
val actor = system.actorOf(
  Props(new ParentActor(testProbe.ref.path.toStringWithoutAddress))
)
val reply = actor ? "Hello"
testProbe.expectMsg("Hello")
testProbe.reply("Hi")
reply.map { res =>
  assert(res == "Hi")
}
© www.soinside.com 2019 - 2024. All rights reserved.