Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play/Scala injecting controller into test

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?

like image 509
Caballero Avatar asked Oct 19 '22 21:10

Caballero


1 Answers

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

like image 66
jazmit Avatar answered Oct 27 '22 11:10

jazmit