我正在为一些CRUD操作在mongodb上创建一个带有喷雾路由的Rest API,这一切都运行得很好,只要我尝试用specs2测试它,就会遵循下面的规范
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)方法
更多信息:
我有一个使用SalatDAO持久化到Mongo的case类。
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")以及我路由的相关部分(删除了错误处理和日志记录):
path("player" / "\\w+".r) {id:String =>
get {
respondWithMediaType(`application/json`) {
complete {
PlayerCRUD.getById(id)
}
}
} ~发布于 2013-03-16 16:41:04
似乎没有人知道,我将_id从ObjectId()改为字符串,并使用helpermethod在需要的地方从新的ObjectId().toString创建它
发布于 2014-09-08 04:25:44
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")
}
}https://stackoverflow.com/questions/15156434
复制相似问题