kotlin - 将 Akka Route TestKit 与 Kotlin Spek 一起使用
问题描述
我正在尝试使用 akka-http-testkit 测试我的 AkkaHTTP 路由(用 Kotlin 编写)。我们项目中的测试使用 Spek,我想保持这种方式。Route TestKit 教程
提供了一个 Java 示例:
public class TestkitExampleTest extends JUnitRouteTest {
TestRoute appRoute = testRoute(new MyAppService().createRoute())
@Test
public void testCalculatorAdd() {
// test happy path
appRoute.run(HttpRequest.GET("/calculator/add?x=4.2&y=2.3"))
.assertStatusCode(200)
.assertEntity("x + y = 6.5")
// test responses to potential errors
appRoute.run(HttpRequest.GET("/calculator/add?x=3.2"))
.assertStatusCode(StatusCodes.NOT_FOUND) // 404
.assertEntity("Request is missing required query parameter 'y'")
// test responses to potential errors
appRoute.run(HttpRequest.GET("/calculator/add?x=3.2&y=three"))
.assertStatusCode(StatusCodes.BAD_REQUEST)
.assertEntity("The query parameter 'y' was malformed:\n" +
"'three' is not a valid 64-bit floating point value")
}
}
设置使用该testRoute
函数,这意味着测试类必须扩展JUnitRouteTest
.
试图翻译成 Kotlin Spek 测试我得到了这个:
class TestKitExampleTest : JUnitRouteTest(), Spek({
describe("My routes") {
val appRoute = testRoute(MyAppService().createRoute())
it("calculator add") {
// test happy path
appRoute.run(HttpRequest.GET("/calculator/add?x=4.2&y=2.3"))
.assertStatusCode(200)
.assertEntity("x + y = 6.5")
//...rest omitted
}
}
})
由于该类试图继承两个类,因此无法编译。我将其转换为以下内容:
class TestKitExampleTest : Spek({
describe("My routes") {
val appRoute = testRoute(MyAppService().createRoute())
it("calculator add") {
// test happy path
appRoute.run(HttpRequest.GET("/calculator/add?x=4.2&y=2.3"))
.assertStatusCode(200)
.assertEntity("x + y = 6.5")
//...rest omitted
}
}
}) {
companion object : JUnitRouteTest()
}
这会遇到运行时错误java.lang.IllegalStateException: Unknown factory null
at akka.http.impl.util.package$.actorSystem(package.scala:34)
。
有没有办法将 Akka 的路由测试包与 Spek 一起使用?还是有另一种方法来测试这些路线?
解决方案
正如上面提到的@raniejade,在 Github 上回答。JUnitRouteTest
使用规则引导 Akka,但 SpekLifeCycleListener
可以做同样的事情。
添加代码:
class SpekRouteBootstrapper: LifecycleListener, JUnitRouteTest() {
override fun beforeExecuteTest(test: TestScope) {
systemResource().before()
}
override fun afterExecuteTest(test: TestScope) {
systemResource().after()
}
}
允许我在测试课上这样做:
class TestKitExampleTest: Spek({
val bootstrapper = SpekRouteBootstrapper()
registerListener(bootstrapper)
describe("My routes") {
val appRoute by memoized {
bootstrapper.testRoute(MyAppService().createRoute())
}
it("calculator add") {
// test happy path
appRoute.run(HttpRequest.GET("/calculator/add?x=4.2&y=2.3"))
.assertStatusCode(200)
.assertEntity("x + y = 6.5")
}
}
})
推荐阅读
- python - 如果内部没有任何抽象方法,那么在 Python 中继承 ABC 类有什么意义吗?
- c# - c# devexpress 用前一行填充当前列
- python - 为 Subprocess.Popen 的 STDOUT 分配多个属性
- ios - 为 ios 模拟器构建,但链接和嵌入式框架 .framework' 是为 ios 构建的
- javascript - Prisma,Next JS api route prisma.create 给了我一个错误的请求
- java - Android LiveData - 对象值未更新
- excel - 根据单元格值自动过滤
- vue.js - Vue:添加新的反应属性的不同选项?
- javascript - 在 Javascript 中输出错误的日期
- angular - 错误:无法匹配任何路由。URL 段:'sockjs-node/info'