【问题标题】:Test AKKA actors that dependant on the future [duplicate]测试依赖于未来的 AKKA 演员 [重复]
【发布时间】:2017-09-29 04:21:08
【问题描述】:

我正在尝试为依赖于 Future 的 actor 编写一个简单的测试。这是几乎不言自明的代码

import akka.actor.{ Actor, ActorSystem, Props }
import akka.testkit.{ ImplicitSender, TestKit }
import org.scalatest.{ BeforeAndAfterAll, WordSpecLike }

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

trait Provider {def get(s: String): Future[String] }

class MyActor(provider: Provider) extends Actor {
  override def receive: Receive = {
    case s: String ⇒
      provider.get(s) map { result: String ⇒
        sender() ! result
      }
  }
}

class FutureTest
  extends TestKit(ActorSystem("Test"))
    with ImplicitSender
    with WordSpecLike
    with BeforeAndAfterAll {

  "MyActor" must {
    "wait for the future" in {
      val myref = system.actorOf(Props(
        new MyActor((s) ⇒ Future { s })
      ))

      myref ! "hello world"

      expectMsg("hello world")
    }
  }
}

期望 msg 不会等待未来完成并失败并显示以下消息:

assertion failed: timeout (3 seconds) during expectMsg while waiting for hello world java.lang.AssertionError: assertion failed: timeout (3 seconds) during expectMsg while waiting for hello world

在我的案例中测试这种行为的最佳做法是什么?

谢谢!

【问题讨论】:

    标签: scala testing concurrency akka future


    【解决方案1】:

    你不应该在传递给未来的回调中关闭sender()。请参阅此 SO 问题,了解为什么以及如何解决:

    sender inside a future

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2013-11-29
      • 2012-07-12
      • 1970-01-01
      相关资源
      最近更新 更多