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

2

13

I'm trying to make sense of the error(s) I'm seeing below, and to learn how to fix it.

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
                                  ^

Here is the test code that produced the error(s):

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

}
Pensioner answered 29/4, 2016 at 18:41 Comment(2)
Try this one: implicit val materializer = ActorMaterializer()Frontwards
Thanks @Mario. I'm not sure where to put that line, though.Pensioner
C
23

You can create an implicit ActorMaterializer within your test class which will use testkit's ActorSystem:

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

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

  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val bbox = ...
Compulsion answered 2/5, 2016 at 14:37 Comment(0)
A
2

You don't need Materializer.

I believe you are calling not the right action.apply method.
You want def apply(request: Request[A]): Future[Result]
To call the right, you need FakeRequest[AnyContent], same parametrized type as action:Action[AnyContent].This type is forced by PlayBodyParser I believe you set for your action.

After that you don't need .run call

Arpeggio answered 23/1, 2018 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.