How to test Action Composition Scala 2.6.x

(Decapo01) #1

From the documentation, there is a UserRequest and UserAction used for Authentication purposes.

import play.api.mvc._

class UserRequest[A](val username: Option[String], request: Request[A]) extends WrappedRequest[A](request)

class UserAction @Inject()(val parser: BodyParsers.Default)(implicit val executionContext: ExecutionContext)
  extends ActionBuilder[UserRequest, AnyContent] with ActionTransformer[Request, UserRequest] {
  def transform[A](request: Request[A]) = Future.successful {
    new UserRequest(request.session.get("username"), request)

I have something similar in my project that uses this:

class MyController @Inject()(userAction: UserAction, cc: ControllerComponents) extends AbstractController(cc) with I18nSupport {

  def index = (userAction) { implicit req =>

How do I now go about testing that? This is what’s in the documentation for testing:

import scala.concurrent.Future


import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._

class ExampleControllerSpec extends PlaySpec with Results {

  "Example Page#index" should {
    "should be valid" in {
      val controller = new ExampleController()
      val result: Future[Result] = controller.index().apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      bodyText mustBe "ok"

How in there can I create a mock UserAction to inject into MyController?

(Marcos Pereira) #2

Hi @decapo01,

The documentation is outdated. I’ve opened a new issue to solve that:

Fell free to contribute if you want.

Regarding how to test, you can use Helpers.stub* methods to create an instance of UserAction and inject it (I’m writing this right here without checking the code, but it should be very similar):

val controllerComponents = Helpers.stubControllerComponents()
val userAction = new UserAction(controllerComponents.parsers.default)(controllerComponents.executionContext)
val controller = new MyController(userAction, controllerComponents)