【问题标题】:Wait until the supervisor is ready before execute the test等到主管准备好再执行测试
【发布时间】:2019-07-03 11:21:25
【问题描述】:

我为我的演员写了一个测试如下:

class DetectorSpec extends BddSpec {

    private val sap = new SapMock()
        .withExposedPorts(8080)
        .waitingFor(Wait.forHttp("/"))

    private val kafka = new KafkaContainer("5.2.1")


    sap.start()
    kafka.start()


    override def afterAll(): Unit = {
        sap.stop()
        kafka.stop()
    }

    private def withKafkaOfflineSapOnline(testCode: TestProbe[ServerEvent] => Unit)
    : Unit = {

        val config = ConfigFactory.parseString(
        s"""
            kafka {
                servers = "127.0.0.1:9092"
            }
            sap {
                server = "ws://${sap.getContainerIpAddress}:${sap.getMappedPort(8080)}"
            }""")

        val testKit = ActorTestKit("testSystem1", config)
        val inbox = testKit.createTestProbe[ServerEvent]("Receiver")
        testKit.spawn(DetectorSupervisor.create(), "DetectorSupervisor")
        testKit.system.receptionist ! Receptionist.Register(ServerStateKey, inbox.ref)

        Thread.sleep(4000)

        testCode(inbox)
        testKit.shutdownTestKit()
    }


    feature("Detect Kafka and SAP availability") {
        scenario("SAP is online and Kafka is offline") {
        withKafkaOfflineSapOnline { inbox =>
                Given("I am waiting for the current state message")
                When("I am receive the state message")
                val msg = inbox.receiveMessage(3.second)
                Then("it should contain `Kafka is offline`")
                msg should be(ServerOnlineApproved)
            }
        }

    }
}

正如您在fixture方法withKafkaOfflineSapOnline中看到的那样,有一个声明Thread.sleep(4000)可以确定, 那个演员DetectorSupervisor 和他们的孩子在考试开始前就准备好了。

有没有更好的方法呢?

如果没有Thread.sleep(4000) 声明,当测试开始时,演员似乎还没有准备好。

【问题讨论】:

    标签: scala akka akka-typed


    【解决方案1】:

    如果您的 actor 仅与您直接控制的 mock 进行通信,并且您在测试中不需要真正的并发,您可以使用 CallingThreadDispatcherConfigurator。当您为单个参与者编写单元测试或希望在测试中使参与者交互具有确定性时,这是有道理的。

    所有异步代码都将在测试线程上运行。因此,当您向参与者发送消息时,您通常可以确保它在测试的下一个语句之前得到处理。

    以下是如何为此目的创建测试套件的示例:

    val config = ConfigFactory.parseString(
    s"""akka.actor.default-dispatcher = {
       |  type = akka.testkit.CallingThreadDispatcherConfigurator
       |}
       |akka.actor.testkit.typed.single-expect-default = 0s
    """.stripMargin
    )
    
    val testKit = ActorTestKit(ActorTestKitBase.testNameFromCallStack(), config)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多