播放/ Scala注入控制器进入测试

时间:2015-11-19 12:46:23

标签: scala playframework guice scalatest playframework-2.4

所以根据Play 2.4文档(https://playframework.com/documentation/2.4.x/ScalaTestingWithScalaTest#Unit-Testing-Controllers),控制器应该设置为这样的特征

trait ExampleController {
  this: Controller =>

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

object ExampleController extends Controller with ExampleController

为了让测试像这样工作

class ExampleControllerSpec extends PlaySpec with Results {

  class TestController() extends Controller with ExampleController

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

然而,我使用Guice依赖注入,并根据Play 2.4文档(https://playframework.com/documentation/2.4.x/ScalaDependencyInjection),我的控制器如下所示:

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

由于控制器不再是特质,我无法将其混合到测试中:with ExampleController,如何使测试成功?

1 个答案:

答案 0 :(得分:3)

您可以直接从ExampleController继承。你也可以删除extends Controller,因为你的控制器已经继承了这个:

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

您可以使用Play和Guice here

找到有关测试的更多信息