因此,根据 Play 2.4 文档(https://playframework.com/documentation/2.4.x/ScalaTestingWithScalaTest#Unit-Testing-Controllers), Controller 应设置为这样的特征
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 依赖注入(inject),根据 Play 2.4 文档(https://playframework.com/documentation/2.4.x/ScalaDependencyInjection),我的 Controller 如下所示:
@Singleton
class ExampleController @Inject() (exampleService: IExampleService) extends Controller {
def index() = Action {
Ok("")
}
}
由于 Controller 不再是一个特征,我不能像这样将它混合到测试中:
with ExampleController
,我如何使上面的测试工作?
最佳答案
您可以直接从 ExampleController 继承。您还可以消除 extends Controller
,因为您的 Controller 已经继承了这个:
class TestController(service: IExampleService) extends ExampleController(service)
您可以找到更多关于使用 Play 和 Guice 进行测试的信息 here
关于scala - Play/Scala 将 Controller 注入(inject)测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33804407/