kotlin - Ktor EmbeddedServer 未在测试中启动
问题描述
在我的 AcceptanceTests 中,我试图通过使用以下非常粗鲁的代码来启动 Ktor EmbeddedServer,以便能够检查服务器是否已启动并且测试是否可以启动:
fun start() {
val configPath = ClassLoader.getSystemResource("application-acceptanceTest.conf").file
val appEnvironment = commandLineEnvironment(arrayOf("-config=$configPath"))
engine = embeddedServer(CIO, appEnvironment)
engine.addShutdownHook {
stop()
}
engine.start()
val disposable = engine.environment.monitor.subscribe(ApplicationStarted) {
started = true
}
while (!started) {
// the start method should not exit until server is started successfully
Thread.sleep(10)
}
disposable.dispose()
}
不幸的是,这在通过 gradle 运行测试时不起作用,但在 IntelliJ 中的单个测试运行期间确实有效。任何提示表示赞赏。
我已经尝试添加一些日志语句,并且我确实看到了 while 循环没有退出,因此我相信 ApplicationStarted-event 没有正确处理。
编辑:删除while循环时,测试使用gradle运行,但不是在IntelliJ :-(
解决方案
所以,这都是关于正确的顺序。它正在使用以下代码块:
fun start() {
val configPath = ClassLoader.getSystemResource("application-acceptanceTest.conf").file
val appEnvironment = commandLineEnvironment(arrayOf("-config=$configPath"))
engine = embeddedServer(CIO, appEnvironment)
engine.addShutdownHook {
stop()
}
val disposable = engine.environment.monitor.subscribe(ApplicationStarted) {
started = true
}
engine.start()
while (!started) {
// the start method should not exit until server is started successfully
Thread.sleep(10)
}
disposable.dispose()
}
我在这里学到的教训是在启动服务器之前首先注册事件侦听器:-)
推荐阅读
- r - 如何为这些回归创建一个循环?
- unit-testing - Mockito 方法调用存根不起作用 - Mockito.doReturn(false).when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());
- python - Python:使用文件夹名称作为键,文件名作为值来制作字典
- java - 在 POSTMAN 中使用 JSON 传递变量时间戳
- python - 如何在python中将JSON字符串转换为整数?
- asp.net-core - 扩展为的方法
- ...
表达 - javascript - 如果网站在 VS2015 中创建为 Visual C# ASP.Net Web 应用程序,则 PageMethods 不起作用
- node.js - 验证码完成后恢复自动化
- reactjs - 如何使反应路由器受到保护?
- git - 如何在 Sourcetree 中取消拉取请求