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

前端之家收集整理的这篇文章主要介绍了scala – 如何正确使用Akka-TestKit TestProbe?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从 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,测试仍然会通过.

猜你在找的Scala相关文章