Play/Scala 将控制器注入测试

Play/Scala injecting controller into test

因此根据 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,我如何使上面的测试工作?

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

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

您可以找到有关使用 Play 和 Guice 进行测试的更多信息here