gpt4 book ai didi

scala - 如何正确使用 Akka-TestKit TestProbe?

转载 作者:行者123 更新时间:2023-12-03 22:02:59 26 4
gpt4 key购买 nike

我从 http://doc.akka.io/docs/akka/snapshot/scala/testing.html#Using_Multiple_Probe_Actors 扩展了示例.

import akka.actor._
import akka.testkit.{TestProbe, TestKit}
import org.scalatest.{Suites, BeforeAndAfter, BeforeAndAfterAll, FlatSpecLike}
import scala.concurrent.duration._

class TestProbesTestSuites extends Suites(new TestProbesTest)

class TestProbesTest extends TestKit(ActorSystem("TestProbesTestSystem")) with FlatSpecLike with BeforeAndAfterAll with BeforeAndAfter {
override def afterAll: Unit = {
TestKit.shutdownActorSystem(system)
}

"A TestProbeTest" should "test TestProbes" in {
val actorRef = system.actorOf(Props[TestActor], "TestActor")
val tester1 = TestProbe()
val tester2 = TestProbe()

Thread.sleep(500.milliseconds.toMillis)

actorRef ! (tester1.ref, tester2.ref)
// When you comment the next line the test fails
tester1.expectMsg(500.milliseconds, "Hello")
tester2.expectMsg(500.milliseconds, "Hello")

// Alternative test
// Thread.sleep(500.milliseconds.toMillis)
// tester1.expectMsg(0.milliseconds, "Hello")
// tester2.expectMsg(0.milliseconds, "Hello")
()
}
}

class TestActor extends Actor with ActorLogging {
override def receive: Receive = {
case (actorRef1: ActorRef, actorRef2: ActorRef) => {
// When you change the schedule time in the next line to 100.milliseconds the test fails
context.system.scheduler.scheduleOnce(400.milliseconds, actorRef1, "Hello")(context.system.dispatcher)
context.system.scheduler.scheduleOnce(800.milliseconds, actorRef2, "Hello")(context.system.dispatcher)
}
case x => log.warning(x.toString)
}
}

我不认为这是测试的正确或良好用法。
当我删除 tester1.expectMsg(500.milliseconds, "Hello")测试失败,
所以tester2的测试依赖于tester1的测试。在我看来这很糟糕。

也在换线 context.system.scheduler.scheduleOnce(400.milliseconds, actorRef1, "Hello")(context.system.dispatcher)延迟 100 毫秒让测试失败。所以测试消息 2 取决于发送消息 1。在我看来,这也很糟糕。

为了解决这个问题,我会在发送消息后添加一个 Thread.sleep 并将 #expectMsg 的等待时间更改为 0 毫秒。 Thread.sleep 在测试中对我来说也不好看,但我认为它在 actor 测试中是必须的。这是正确的方法吗?

我认为 TestProbe 是为测试多个 Actor 而设计的。但是对我来说,在测试多个参与者时,#expectMsg 的等待时间参数是非常无用的。

欢迎提出任何意见。

最佳答案

你可以试试 within像这样阻止:

within(800.milliseconds, 900.milliseconds){
tester1.expectMsg("Hello")
tester2.expectMsg("Hello")
}

这样,如果您将断言注释掉 tester1测试仍然通过。

关于scala - 如何正确使用 Akka-TestKit TestProbe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31806685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com