无法使用 Action.async 测试控制器 [英] Unable to test controller using Action.async
问题描述
我正在尝试测试使用新 Action.async
的控制器.遵循 documentation 我已经排除了控制器下的部分我想测试以将特征与类型引用分开:
I'm trying to test controller, which is using new Action.async
. Following documentation I have excluded part under controller I want to test to separate trait with type reference:
trait UserController { this: Controller =>
def index() = Action { /* snip */ }
def register() = Action.async(parse.json) { request => /* snip */ }
}
文档说明我应该将其测试为:
Documentation states that I'm supposed to test it as:
object UsersControllerSpec extends PlaySpecification with Results {
class TestController() extends Controller with UserController
"index action" should {
"should be valid" in {
val controller = new TestController()
val result: Future[SimpleResult] = controller.index().apply(FakeRequest())
/* assertions */
}
}
}
}
对于 index()
方法它工作得很好,不幸的是我不能用 register()
做同样的事情,因为在它上面应用 FakeRequest 返回 Iteratee[Array[Byte], SimpleResult]
.我注意到它有返回 Future[SimpleResult]
的 run()
方法,但无论我如何构建 FakeRequest
它都会返回 400
没有任何内容或标题.在我看来,FakeRequest
的内容完全被忽略了.我应该以某种方式将请求正文提供给 iteratee 然后运行它吗?我找不到任何示例,我该怎么做.
For index()
method it works perfectly, unfortunately I'm not able to do the same with register()
, as applying FakeRequest on it returns instance of Iteratee[Array[Byte], SimpleResult]
. I've noticed it has run()
method that returns Future[SimpleResult]
but no matter how I build FakeRequest
it returns with 400
without any content or headers. Seems to me like content of FakeRequest
is disregarded at all. Am I supposed to feed request body to iteratee somehow and then run it? I couldn't find any example how could I do that.
推荐答案
对我来说是这样的:
import concurrent._
import play.api.libs.json._
import play.api.mvc.{SimpleResult, Results, Controller, Action}
import play.api.test._
import ExecutionContext.Implicits.global
trait UserController {
this: Controller =>
def index() = Action {
Ok("index")
}
def register() = Action.async(parse.json) {
request =>
future(Ok("register: " + request.body))
}
}
object UsersControllerSpec extends PlaySpecification with Results {
class TestController() extends Controller with UserController
"register action" should {
"should be valid" in {
val controller = new TestController()
val request = FakeRequest().withBody(Json.obj("a" -> JsString("A"), "b" -> JsString("B")))
val result: Future[SimpleResult] = controller.register()(request)
/* assertions */
contentAsString(result) === """register: {"a":"A","b":"B"}"""
}
}
}
这篇关于无法使用 Action.async 测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!