加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:01:56 所属栏目:安全 来源:网络整理
导读:我从 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}i
我从 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”)时,测试失败,
所以test2的测试依赖于测试tester1.在我看来这很糟糕.

同时将行context.system.scheduler.scheduleOnce(400.milliseconds,“Hello”)(context.system.dispatcher)更改为100毫秒的延迟,让测试失败.所以测试消息2取决于发送消息1.在我看来,这也很糟糕.

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

我认为TestProbe是为测试多个演员而设计的.但对我来说,#expectMsg的等待时间参数在测试多个actor时非常无用.

欢迎任何评论.

解决方法

你可以尝试一个内部块,如下所示:

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

这样,如果你将这个断言注释给tester1,测试仍然会通过.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读