1

我正在尝试使用 akka.http.scaladsl.testkit.responseAs 来测试一些端点,但我不知道如何处理 org.joda.time.DateTime 对象的编组/解组过程。例如,考虑下面的案例类:

case class ConfigEntity(id: Option[Int] = None, description: String, key: String, value: String, expirationDate: Option[DateTime] = None)

另外,请考虑以下路线测试:

"retrieve config by id" in new Context {
  val testConfig = testConfigs(4)
  Get(s"/configs/${testConfig.id.get}") ~> route ~> check {
    responseAs[ConfigEntity] should be(testConfig)
  }
}

当我运行“sbt test”时,代码无法编译,抛出以下错误:“找不到akka.http.scaladsl.unmarshalling.FromResponseUnmarshaller[me.archdev.restapi.models.ConfigEntity] 类型的证据参数的隐式值"

我知道该消息非常不言自明,但我仍然不知道如何创建代码抱怨的隐式 FromResponseUnmarshaller。

我的代码基于此示例:https ://github.com/ArchDev/akka-http-rest

我只是在创建一些新实体并尝试玩...

提前致谢。

4

1 回答 1

0

该项目使用 CirceSupport。这意味着您需要为编译器提供一个 Circe 解码器来派生 Akka Http Unmarshaller。

将解码器放在范围内:

case class ConfigEntity(id: Option[Int] = None, description: String, key: String, value: String, expirationDate: Option[DateTime] = None)

implicit val decoder = Decoder.decodeString.emap[DateTime](str =>
  Right(DateTime.parse(str))
)

"retrieve config by id" in new Context {
  val testConfig = testConfigs(Some(4))
  Get(s"/configs/${testConfig.id.get}") ~> route ~> check {
    responseAs[ConfigEntity] should be(testConfig)
  }
}

显然,您必须处理尝试解析 DateTime 并返回 Left 而不是 Right 的可能异常...

我必须说我总是使用 SprayJsonSupport 来支持 Akka Http,这是我第一次看到 CirceSupport。

希望这可以帮助。

于 2017-06-21T15:05:03.973 回答