如何使用喷雾路由测试自定义Json对象 [英] Howto test Custom Json Objects with Spray Routing

查看:99
本文介绍了如何使用喷雾路由测试自定义Json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在mongodb之上创建一个带有喷雾路由的Rest API,用于某些CRUD操作,一切正常,希望每当我尝试使用specs2
以下规范对其进行测试

I'm creating a Rest API with spray-routing on top of mongodb for some CRUD operations, this all works fine, expect whenever I try to test it with specs2 the following specification

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
}

它将失败,并显示以下错误:

it will fail with the following error:

MalformedContent(invalid ObjectId ["51308c134820cf957c4c51ca"],Some(java.lang.IllegalArgumentException: invalid ObjectId ["51308c134820cf957c4c51ca"])) (Specs2Interface.scala:25)

我不知道在哪里寻找对源文件的引用,并且行号指向通用的failTest(msg :String)方法

I have no idea where to look as the reference to the source file and line number point to a generic failTest(msg:String) method

更多信息:

我有一个案例类,我使用SalatDAO坚持使用Mongo

I have a case class that I persist to Mongo using SalatDAO

case class Player(@Key("_id") _id:ObjectId = new ObjectId(), name:String, email:String, age:Int) {}

其中ObjectId()是包装mongodb的ID生成类的类
通过Spray_json将其解组,我创建了一些jsonF ormats

where ObjectId() a class is that wraps mongodb's ID generation to get this (un)marshalled through spray_json I created some 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")

以及我路线的相关部分(已删除的错误处理和日志记录):

and the relevant part of my route (removed error handling and logging):

  path("player" / "\\w+".r) {id:String =>
    get {
      respondWithMediaType(`application/json`) {
        complete {
          PlayerCRUD.getById(id) 
        }
      }
    } ~


推荐答案

似乎没人知道,我更改了_id从成为一个ObjectId()到只是一个字符串,并有一个帮助方法可以根据需要从新的ObjectId()。toString创建它

As nobody seems to know, I changed the _id from being a ObjectId() to just a string, and having a helpermethod to create it from new ObjectId().toString where needed

这篇关于如何使用喷雾路由测试自定义Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆