12

我正在尝试测试使用 new 的控制器Action.async。按照文档,我已经排除了控制器下的部分,我想测试以将特征与类型引用分开:

trait UserController { this: Controller =>
  def index() = Action { /* snip */ }
  def register() = Action.async(parse.json) { request => /* snip */ }
}

文档指出我应该将其测试为:

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()Iteratee[Array[Byte], SimpleResult]. 我注意到它有run()返回的方法,Future[SimpleResult]但无论我如何构建FakeRequest它都返回400没有任何内容或标题。在我看来,内容FakeRequest完全被忽视了。我是否应该以某种方式将请求正文提供给 iteratee 然后运行它?我找不到任何例子,我该怎么做。

4

2 回答 2

9

出现这个问题是因为play.api.mvc.Action[A]包含了这两个apply方法:

// 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在这种情况下,一切都不同了。如果它不是正确的类型,你最终会调用错误的apply.

当您使用ActionBuilderaBodyParser[A]时,您会创建一个Action[A]. 因此,您需要Request[A]进行测试。parse.json返回 a BodyParser[JsValue],所以你需要 a Request[JsValue]

// In FakeRequest object
def apply(): FakeRequest[AnyContentAsEmpty.type]

FakeRequest()没有得到你需要的类型。幸运的是:

// In FakeRequest class
def withBody[B](body: B): FakeRequest[B]

因此,开始使用正文的占位符来编写测试:

  "should be valid" in {
    val controller = new TestController()
    val body: JsValue = ??? // Change this once your test compiles

    // Could do these lines together, but this shows type signatures
    val request: Request[JsValue] = FakeRequest().withBody(body)
    val result: Future[Result] = controller.index().apply(request)

    /* assertions */
  }
于 2014-09-02T04:44:12.843 回答
7

对我来说是这样的:

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"}"""
    }
  }
}
于 2013-10-18T18:15:20.280 回答