首页 > 解决方案 > 将 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 一起使用?还是有另一种方法来测试这些路线?

标签: kotlinakkaakka-http

解决方案


正如上面提到的@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")
    }
  }
})

推荐阅读