【问题标题】:Test code from Akka documentation runs strangelyAkka 文档中的测试代码运行异常
【发布时间】:2017-10-23 10:51:44
【问题描述】:

我正在学习 Akka 演员模型中的测试方法。我试图从 Akka 文档中运行一些代码。当我运行以下代码时,会出现一个令人困惑的错误。我正在使用 JDK 1.8.121、macOS 和 Scala 2.12。

来自Akka documentation的代码:

val probe = TestProbe()
val future = probe.ref ? "hello"
probe.expectMsg(0 millis, "hello") // TestActor runs on CallingThreadDispatcher
probe.reply("world")
assert(future.isCompleted && future.value == Some(Success("world")))

我在自己的电脑上设置了测试:

package TestKitDemo

import akka.actor.ActorSystem
import akka.actor.Status.Success
import akka.testkit.{TestKit, TestProbe}
import org.scalatest.{BeforeAndAfterAll, WordSpecLike}
import akka.pattern.ask
import akka.util.Timeout

import scala.concurrent.duration._
import scala.util.Try

class ReplyDemo extends TestKit(ActorSystem("Testsystem")) with WordSpecLike
with BeforeAndAfterAll{
//  import system.dispatcher
  override protected def afterAll(): Unit = {
    shutdown(system)
  }

  implicit val timeout = Timeout(2 seconds)
  "reply" should {
    "same" in {

      val probe = TestProbe()
      val future = probe.ref ? "hello"
      probe.expectMsg(0 millis, "hello") // TestActor runs on CallingThreadDispatcher
      probe.reply("world")


      // error
      assert(future.isCompleted && future.value == Some(Success("world")))

      // correct
//      assert(future.isCompleted && future.value.get == Try("world"))

    }
  }
}

我使用了两种assert:一种是Akka documentation中的代码,另一种是我自己使用Try进行的相等性测试。

我知道Try 是什么。据我所知,Try 是一种可以是SuccessFailure 的类型。

测试错误如下:

future.isCompleted was true, but Some(Success("world")) did not equal Some(Success(world))
ScalaTestFailureLocation: TestKitDemo.ReplyDemo at (ReplyDemo.scala:44)
Expected :Some(Success(world))
Actual   :future.isCompleted was true, but Some(Success("world"))

Some(Success("world")) 不等于 Some(Success(world))。怎么了?他们应该是平等的。

【问题讨论】:

    标签: scala akka actor akka-testkit


    【解决方案1】:
    assert(future.isCompleted && future.value == Some(Success("world")))
    

    上述断言在您的测试中失败的原因是您尝试匹配akka.actor.Status.Success 而不是scala.util.Success。替换

    import akka.actor.Status.Success
    

    import scala.util.Success
    

    你的测试就会通过。

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 2019-09-27
      • 1970-01-01
      • 2020-12-07
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多