无法使用Action.async测试控制器 [英] Unable to test controller using Action.async

查看:150
本文介绍了无法使用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"}"""
    }
  }
}

这篇关于无法使用Action.async测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆