Play/Scala注入控制器进入测试 [英] Play/Scala injecting controller into test
问题描述
因此,根据Play 2.4文档( https://playframework.com /documentation/2.4.x/ScalaTestingWithScalaTest#Unit-Testing-Controllers ),则应将控制器设置为这样的特征
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
为了使测试能够像这样
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 ),我的控制器如下所示:
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("")
}
}
由于控制器不再是特征,因此我无法将其混入测试中:with ExampleController
,如何使上面的测试正常工作?
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?
推荐答案
您可以直接从ExampleController继承.您还可以消除extends Controller
,因为您的控制器已经继承了此内容:
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)
您可以在此处
这篇关于Play/Scala注入控制器进入测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!