Play/Scala injecting controller into test
Asked Answered
P

1

6

So according to Play 2.4 documentation (https://playframework.com/documentation/2.4.x/ScalaTestingWithScalaTest#Unit-Testing-Controllers), the controller should be set up as a trait like this

trait ExampleController {
  this: Controller =>

  def index() = Action {
    Ok("ok")
  }
}

object ExampleController extends Controller with ExampleController

in order for a test to work like this

class ExampleControllerSpec extends PlaySpec with Results {

  class TestController() extends Controller with ExampleController

  "Example Page#index" should {
    "should be valid" in {
        //test code
    }
  }
}

however, I'm using Guice dependency injection, and according to Play 2.4 documentation (https://playframework.com/documentation/2.4.x/ScalaDependencyInjection) my controller looks like this:

@Singleton
class ExampleController @Inject() (exampleService: IExampleService) extends Controller {
    def index() = Action {
        Ok("")
    }
}

Since controller is no longer a trait and I can't mix it into the test like this: with ExampleController, how do I make the test above work?

Polaroid answered 19/11, 2015 at 12:46 Comment(0)
K
4

You can inherit directly from ExampleController. You can also eliminate the extends Controller, as your controller already inherits this:

class TestController(service: IExampleService) extends ExampleController(service)

You can find more information about testing using Play and Guice here

Kilter answered 19/11, 2015 at 15:48 Comment(3)
Thanks. By the way, any idea how to inject the service (that is injected into the controller) into the same test as well?Polaroid
I'd mock out the service, eg: using ScalaMock.Kilter
I don't understand, what would be the benefit of creating a class TestController and testing it, instead of testing the ExampleController directy?Freon

© 2022 - 2024 — McMap. All rights reserved.