如何使用Spray Routing测试自定义Json对象

时间:2013-03-01 11:18:13

标签: routing casbah salat spray-json testkit

我正在mongodb上创建一个带有喷涂路由的Rest API用于某些CRUD操作,这一切都运行正常,每当我尝试使用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编译(un)编组我创建了一些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) 
        }
      }
    } ~

2 个答案:

答案 0 :(得分:3)

似乎没有人知道,我将_id从ObjectId()更改为只是一个字符串,并使用helper方法从新的ObjectId()创建它.toString在需要的地方

答案 1 :(得分:1)

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