scala - 等到主管准备好再执行测试
问题描述
我为我的演员写了一个测试如下:
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)
}
}
}
}
正如您在夹具方法中看到的那样withKafkaOfflineSapOnline
,有一个声明Thread.sleep(4000)
可以确保DetectorSupervisor
在测试开始之前,带有孩子的演员已经准备好。
有更好的方法吗?
如果没有Thread.sleep(4000)
声明,当测试开始时,演员似乎还没有准备好。
解决方案
如果您的 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)
推荐阅读
- php - 无法从 getJSON / PHP 加载 Chart.js 数据?
- java - Quarkus:如何使用新实例更新实体?
- schema.org - https://schema.org/ - 是@id 保存在网站的所有页面上
- c - SWIG 将多个数组从 python 传递到 C
- persistence - 在 Aurelia Store 中执行状态持久化
- react-native - 我无法在本机反应中收到最新 android 版本(> 6)的推送通知
- javascript - 占位符删除焦点(不带 jq)
- python - 将 Python 字典转换为 .csv 文件
- sql - 通过从以前的记录中减去金额来计算余额
- windows - 为什么“插入包含批处理文件的软盘并在准备好时按任意键”。消息出现?