Play/Scala injecting controller into test

…衆ロ難τιáo~ 提交于 2019-12-07 05:16:53

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/33804407/play-scala-injecting-controller-into-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!