加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – play框架2:使用json字符串作为正文测试请求

发布时间:2020-12-16 18:54:07 所属栏目:安全 来源:网络整理
导读:我有以下行动 def save() = Action(parse.json) { implicit request = request.body.asOpt[IdeaType].map { ideatype = ideatype.save.fold( errors = JsonBadRequest(errors),ideatype = Ok(toJson(ideatype)) ) }.getOrElse (JsonBadRequest("Invalid type
我有以下行动

def save() = Action(parse.json) { implicit request =>
  request.body.asOpt[IdeaType].map { ideatype =>
    ideatype.save.fold(
      errors => JsonBadRequest(errors),ideatype => Ok(toJson(ideatype))
    )
  }.getOrElse     (JsonBadRequest("Invalid type of idea entity"))
}

我想测试一下

Web服务正常运行,如下所示:

curl -X post "http://localhost:9000/api/types" 
--data "{"name": "new name","description": "new description"}" 
--header "Content-type: application/json"

正确返回新资源

{"url":"/api/types/9","id":9,"name":"new name","description":"new description"}

我正试着用它来测试它

"add a new ideaType,using route POST /api/types" in {
  running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {

    val json = """{"name": "new name","description": "new description"}"""

    val Some(result) = routeAndCall(
      FakeRequest(
        POST,"/api/types",FakeHeaders(Map("Content-Type" -> Seq("application/json"))),json
      )
    )

    status(result) must equalTo(OK)
    contentType(result) must beSome("application/json")
    val Some(ideaType) = parse(contentAsString(result)).asOpt[IdeaType]

    ideaType.name mustEqual "new name"

  }
}

但是我收到以下错误:

[error] ! add a new ideaType,using route POST /api/types
[error]     ClassCastException: java.lang.String cannot be cast to play.api.libs.json.JsValue (IdeaTypes.bak.scala:35)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:36)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:35)
[error] play.api.mvc.Action$$anon$1.apply(Action.scala:170)

我按照这个问题的建议:Play 2 – Scala FakeRequest withJsonBody

我错过了什么吗?

Kim Stebel解决方案运行良好,但后来我尝试使用withJsonBody,如下所示:

val jsonString = """{"name": "new name","description": "new description"}"""
    val json: JsValue = parse(jsonString)

    val Some(result) = routeAndCall(
      FakeRequest(POST,"/api/types").
      withJsonBody(json)
    )

我收到以下错误:

[error] ! add a new ideaType,using route POST /api/types
[error]     ClassCastException: play.api.mvc.AnyContentAsJson cannot be cast to play.api.libs.json.JsValue (IdeaTypes.bak.scala:35)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:36)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:35)

任何的想法?

解决方法

您可能需要传入JsValue作为请求的主体.改变线

val json = """{"name": "new name","description": "new description"}"""

val jsonString = """{"name": "new name","description": "new description"}"""
val json = Json.parse(jsonString)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读