发送FakeRequest时如何为akka.stream.Materializer提供隐含值?

时间:2016-04-29 18:41:54

标签: scala playframework playframework-2.0 akka akka-stream

我试图理解我在下面看到的错误,并学习如何解决它。

could not find implicit value for parameter materializer: akka.Stream.Materializer
  val fut: Future[Result] = action.apply(fakeRequest).run
                                  ^
not enough arguments for method run (implicit materializer: akka.stream.Materializer)scala.concurrent.Future[play.api.mvc.Result].
Unspecified value parameter materializer.
  val fut: Future[Result] = action.apply(fakeRequest).run
                                  ^

以下是产生错误的测试代码:

package com.foo.test

import com.foo.{Api, BoundingBox}
import org.scalatest.{FlatSpec, Matchers}
import play.api.libs.json._
import play.api.mvc._
import play.api.test.{FakeHeaders, FakeRequest}

import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

class TestJmlPlay extends FlatSpec with Matchers {

  val bbox = new BoundingBox(-76.778154438007732F, 39.239828198015971F, -76.501003519894326F, 39.354663763993926F)

  "latitudes" should "be between swLat and neLat" in {
    val action: Action[AnyContent] = (new Api).getForPlay(bbox)
    val jsonStr = getStringFromAction(action)
    areLatitudesOk(jsonStr, bbox) shouldBe true
  }

  private def getStringFromAction(action:Action[AnyContent]):String = {
    val fakeRequest: Request[String] = new FakeRequest("fakeMethod", "fakeUrl", new FakeHeaders, "fakeBody")
    val fut: Future[Result] = action.apply(fakeRequest).run  // <== ERROR!
    val result = Await.result(fut, 5000 milliseconds)
    result.body.toString
  }

  private def areLatitudesOk(jsonStr: String, bbox: BoundingBox): Boolean = ...

}

2 个答案:

答案 0 :(得分:18)

您可以在测试类中创建一个隐式ActorMaterializer,它将使用testkit&#39; s ActorSystem

import akka.testkit.TestKit
import akka.actor.ActorSystem

class TestJmlPlay(_system : ActorSystem) extends TestKit(_system) ... {

  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val bbox = ...

答案 1 :(得分:2)

您不需要Materializer。

我相信你不是正确的action.apply方法 你想要def apply(request: Request[A]): Future[Result]
要调用右边,你需要FakeRequest[AnyContent],与action:Action[AnyContent]相同的参数化类型。这种类型是由PlayBodyParser强制的,我相信你会为你的行动设置。

之后您不需要.run来电