gpt4 book ai didi

scala - 如何使用 Json BodyParser 测试 Play REST API?

转载 作者:行者123 更新时间:2023-12-02 00:36:14 25 4
gpt4 key购买 nike

我想为 Controller 编写一个简单的测试,它接受一个 json 主体。但是一旦我将 parse.json BodyParser 添加到 Action 中,我的测试就无法再编译了。安装程序基本上是普通的 play-scala-seed 项目。

错误:

[error] ... could not find implicit value for parameter mat: akka.stream.Materializer
[error] status(home) mustBe OK
[error] ^

家庭 Controller :

def index() = Action { implicit request =>
Ok
}

def json() = Action(parse.json) { implicit request =>
Ok
}

HomeControllerSpec:

class HomeControllerSpec extends PlaySpec with GuiceOneAppPerTest with Injecting {
"HomeController POST" should {
"answer Ok" in {
val controller = new HomeController(stubControllerComponents())
val home = controller.json().apply(FakeRequest(POST, "/"))
status(home) mustBe OK
}
}

最佳答案

关于 stubControllerComponentsFakeRequest 调用的相关代码似乎存在两个问题。

Helpers.stubControllerComponents默认情况下使用 NoMaterializer 构造 ControllerComponents它在使用时只会抛出一个异常,所以我们需要提供一个实际的物化器,如下所示:

       implicit val materializer = ActorMaterializer()(ActorSystem())

Helpers.stubControllerComponents(
playBodyParsers = Helpers.stubPlayBodyParsers(materializer)
)

第二个问题是关于 FakeRequest 的,我们需要提供一个正文如下(否则我们会得到 4xx 错误):

FakeRequest(POST, "/json").withBody(Json.obj("name" -> "Jon Doe"))

考虑到以上我们可以编写完整的测试如下:

class HomeControllerSpec extends PlaySpec with GuiceOneAppPerTest {
"HomeController POST" should {
"answer Ok" in {
implicit val materializer = ActorMaterializer()(ActorSystem())

val controllerComponents =
Helpers.stubControllerComponents(
playBodyParsers = Helpers.stubPlayBodyParsers(materializer)
)

val controller = new HomeController(controllerComponents)

val fakeRequest =
FakeRequest(POST, "/json").withBody(Json.obj("name" -> "Jon Doe"))

val home = call(controller.json(), fakeRequest)

status(home) mustBe OK
}
}
}

关于scala - 如何使用 Json BodyParser 测试 Play REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410088/

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