无法使用Action.async测试控制器
我正在尝试测试使用新的Action.async
的控制器.在文档之后,我排除了控制器下要测试的类型部分,以使用类型引用分隔特征:
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"}"""
}
}
}