将Iteratee转换为结果 [英] convert Iteratee to Result
问题描述
我正在为我的游戏应用程序控制器编写测试用例,但无法获得操作结果.
I am writing test-cases for my play application controller, and I am having trouble getting the action result.
val jsonresult = UserController.importOPML()(
FakeRequest(POST, "/user/import-opml",FakeHeaders(),data)
.withCookies(cookie)
)
这仅在将Action指定为parse.multipartFormData
时有效,如果将其更改为parse.json
this would work only when the Action is specified parse.multipartFormData
, if it is changed to parse.json
类型不匹配;找到:play.api.libs.iteratee.Iteratee [Array [Byte],play.api.mvc.SimpleResult]必需: scala.concurrent.Future [play.api.mvc.SimpleResult]
type mismatch; found : play.api.libs.iteratee.Iteratee[Array[Byte],play.api.mvc.SimpleResult] required: scala.concurrent.Future[play.api.mvc.SimpleResult]
我不知道为什么,所以我改成
I don't know why , so I changed to
val Some(jsonresult ) = route( request )
这次编译可以通过,但是我的身份验证存根不能再通过.是什么导致该奇怪的错误?以及如果使用路由,为什么cookie不起作用.
this time the compilation can pass, but my Authentication stub cannot pass anymore. what is causing that weird error ? and if work with route, why the cookie didn't work.
推荐答案
之所以会出现此问题,是因为play.api.mvc.Action[A]
包含以下两个apply方法:
This problem arises because play.api.mvc.Action[A]
contains these two apply methods:
// What you're hoping for
def apply(request: Request[A]): Future[Result]
// What actually gets called
def apply(rh: RequestHeader): Iteratee[Array[Byte], Result]
Request[A] extends RequestHeader
,因此在这种情况下,A
发挥了所有作用.如果它与操作不匹配,则会调用错误的方法.
Request[A] extends RequestHeader
, so the A
in this case makes all the difference. If it doesn't match the action, you'll call the wrong method.
如果您的操作是Action[AnyContent]
,则必须传递Request[AnyContent]
-Request[AnyContentAsJson]
可以,但是FakeRequest[JsValue]
无效,因为只有前者是Request[AnyContent]
.
If your action is a Action[AnyContent]
, then you must pass a Request[AnyContent]
- Request[AnyContentAsJson]
will work, but FakeRequest[JsValue]
won't, because only the former is a Request[AnyContent]
.
当将ActionBuilder
与BodyParser[A]
一起使用时,将创建一个Action[A]
.结果,您需要一个Request[A]
进行测试,这意味着问题中data
的类型至关重要.
When you use ActionBuilder
with a BodyParser[A]
, you create an Action[A]
. As a result, you'll need a Request[A]
to test, which means that the type of data
in your question is critically important.
-
parse.json
返回BodyParser[JsValue]
,因此data
必须是JsValue
-
parse.multipartFormData
返回一个BodyParser[MultipartFormData[TemporaryFile]]
,因此data
必须是多部分表单数据.
parse.json
returns aBodyParser[JsValue]
, sodata
must be aJsValue
parse.multipartFormData
returns aBodyParser[MultipartFormData[TemporaryFile]]
, sodata
must be multi-part form data.
(注意:自从您问这个问题已经有一段时间了,所以我是使用Play 2.3而不是您被问到的2.2来回答这个问题的.)
这篇关于将Iteratee转换为结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!