如何使用喷雾路由测试自定义Json对象



我正在为mongodb的一些CRUD操作创建一个带有喷雾路由的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) 
        }
      }
    } ~

似乎没有人知道,我改变了_id从一个ObjectId()只是一个字符串,并有一个帮助方法来创建它从新的ObjectId()。

 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")
    }
  }

相关内容

  • 没有找到相关文章

最新更新