Scoda中的Joda编组/解组

时间:2017-06-19 20:33:44

标签: scala testing scala-implicits

我尝试使用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

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

提前致谢。

1 个答案:

答案 0 :(得分: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而不是......

我必须说我总是将SprayJsonSupport用于Akka Http,这是我第一次见到CirceSupport。

希望这有帮助。