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

How do I supply an implicit value for an akka.stream.Materializer when sending a FakeRequest?

我正在尝试弄清楚我在下面看到的错误,并学习如何修复它。

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 = ...

}

您可以在测试 class 中创建一个隐式 ActorMaterializer,它将使用测试套件的 ActorSystem:

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

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

  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val bbox = ...

您不需要 Materializer。

我认为您调用的 action.apply 方法不正确。
你想要 def apply(request: Request[A]): Future[Result]
要正确调用,您需要 FakeRequest[AnyContent],与 action:Action[AnyContent] 相同的参数化类型。此类型由 PlayBodyParser 强制执行,我相信您已为您的操作设置。

之后你就不需要.run调用