Routing 如何使用喷洒路由测试自定义Json对象
我正在为一些CRUD操作创建一个RESTAPI,在mongodb的顶部使用spray路由,这一切都很好,只要我尝试使用specs2测试它就可以了 以下规格Routing 如何使用喷洒路由测试自定义Json对象,routing,casbah,salat,spray-json,testkit,Routing,Casbah,Salat,Spray Json,Testkit,我正在为一些CRUD操作创建一个RESTAPI,在mongodb的顶部使用spray路由,这一切都很好,只要我尝试使用specs2测试它就可以了 以下规格 class RestServiceSpec extends Specification with Specs2RouteTest with RoutingRestService // database initialization removed for clarity "The rest service" should
class RestServiceSpec extends Specification with Specs2RouteTest with RoutingRestService
// database initialization removed for clarity
"The rest service" should
"have a player called 'Theo TestPlayer' in the db" in {
Get("/api/1.0/player/" + player1._id) ~> restRoute ~> check {
entityAs[Player] must be equalTo(player1)
}
}
}
// some more specs removed for clarity
}
它将失败,并出现以下错误:
MalformedContent(invalid ObjectId ["51308c134820cf957c4c51ca"],Some(java.lang.IllegalArgumentException: invalid ObjectId ["51308c134820cf957c4c51ca"])) (Specs2Interface.scala:25)
由于对源文件和行号的引用指向一个通用的failTest(msg:String)方法,我不知道在哪里查找
更多信息:
我有一个case类,我使用SalatDAO坚持使用Mongo
case class Player(@Key("_id") _id:ObjectId = new ObjectId(), name:String, email:String, age:Int) {}
其中ObjectId()是封装mongodb ID生成的类
为了通过spray_json对其进行编组,我创建了一些jsonFormats
object MyJsonProtocol {
implicit val objectIdFormat = new JsonFormat[ObjectId] {
def write(o:ObjectId) = JsString(o.toString)
def read(value:JsValue) = new ObjectId(value.toString())
}
implicit val PlayerFormat = jsonFormat(Player, "_id", "name", "email", "age")
以及我的路线的相关部分(已删除错误处理和日志):
似乎没有人知道,我将_id从ObjectId()更改为一个字符串,并使用一种帮助方法从新的ObjectId()创建它。在需要时使用字符串谢谢。我也遇到了同样的问题,通过阅读您的问题和答案,我成功地解决了这个问题:)spray json格式化程序是围绕编写格式化程序的能力构建的,它已经为所有默认类型提供了格式化程序,因此只需要为它不支持的类型提供格式化程序
implicit object ObjectIdJsonFormat extends JsonFormat[ObjectId] {
def write(obj: ObjectId): JsValue = JsString(obj.toString)
def read(json: JsValue): ObjectId = json match {
case JsString(str) => new ObjectId(str)
case _ => throw new DeserializationException(" string expected")
}
}
implicit object ObjectIdJsonFormat extends JsonFormat[ObjectId] {
def write(obj: ObjectId): JsValue = JsString(obj.toString)
def read(json: JsValue): ObjectId = json match {
case JsString(str) => new ObjectId(str)
case _ => throw new DeserializationException(" string expected")
}
}