gpt4 book ai didi

scala - Play Framework 2 : test a request with a json string as body

转载 作者:行者123 更新时间:2023-11-28 19:46:54 25 4
gpt4 key购买 nike

我有以下操作

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 正常工作:

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)

关于scala - Play Framework 2 : test a request with a json string as body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com