将 Akka Route TestKit 与 Kotlin Spek 结合使用

Using Akka Route TestKit with Kotlin Spek

我正在尝试使用 akka-http-testkit 测试我的 AkkaHTTP 路由(用 Kotlin 编写)。我们项目中的测试使用 Spek,我想保持这种方式。
Route TestKit tutorial 给出了一个 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函数,这意味着测试class必须扩展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 试图继承两个 classes。我将其转换为以下内容:

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)

有没有办法在 Spek 中使用 Akka 的路由测试包?或者有其他方法可以测试这些路线吗?

正如上面提到的@raniejade,在 Github 上回答。 JUnitRouteTest 使用规则引导 Akka,但 Spek 的 LifeCycleListener 可以做同样的事情。

添加代码:

class SpekRouteBootstrapper: LifecycleListener, JUnitRouteTest() {
  override fun beforeExecuteTest(test: TestScope) {
    systemResource().before()
  }

  override fun afterExecuteTest(test: TestScope) {
    systemResource().after()
  }
} 

允许我在测试中这样做 class:

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")
    }
  }
})