【问题标题】:How do I supply an implicit value for an akka.stream.Materializer when sending a FakeRequest?发送 FakeRequest 时如何为 akka.stream.Materializer 提供隐式值?
【发布时间】:2016-08-25 00:46:59
【问题描述】:

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

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

}

【问题讨论】:

  • 试试这个:implicit val materializer = ActorMaterializer()
  • 谢谢@Mario。不过,我不确定该放在哪里。

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


【解决方案1】:

你可以在你的测试类中创建一个隐含的ActorMaterializer,它将使用testkit的ActorSystem

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

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

  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val bbox = ...

【讨论】:

    【解决方案2】:

    你不需要 Materializer。

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

    之后你就不需要.run打电话了

    【讨论】:

      猜你喜欢
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 2020-06-22
      • 2021-05-19
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多