我正在为一些 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 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)
}
}
} ~
最佳答案
似乎没有人知道,我将 _id 从一个 ObjectId() 更改为一个字符串,并在需要时使用辅助方法从 new ObjectId().toString 创建它
关于routing - 如何使用 Spray Routing 测试自定义 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15156434/