我的应用程序依赖于从特征SystemComponent继承的自定义类。
package com.example
trait SystemWrapper { ... }
trait MySystemWrapper extends SystemWrapper { ... }
class RealSystemWrapper extends MySystemWrapper { dao: RealDAOFactory =>
val blah = new MySystem("Production")
}在我的Application.scala中,注入RealSystemWrapper可以很好地工作和编译,但是对我的测试没有帮助:
class Application @Inject() (syswrap: RealSystemWrapper) extends Controller
{
...// use syswrap here
}我想使用一个带有模拟DAO工厂等的MockedSystemWrapper extends SystemWrapper。因此,我想像这样注入特征SystemWrapper
class Application @Inject() (syswrap: SystemWrapper) extends Controller
{ 但是我得到了ProvisionException:没有绑定任何实现
1) No implementation for com.example.SystemWrapper was bound.
while locating com.example.SystemComponent
for parameter 0 at com.example.controllers.Application.<init>(Application.scala:25)
while locating com.example.controllers.Application
for parameter 1 at router.Routes.<init>(Routes.scala:27)
while locating router.Routes
while locating play.api.inject.RoutesProvider
while locating play.api.routing.Router
for parameter 0 at play.api.http.JavaCompatibleHttpRequestHandler.<init>(HttpRequestHandler.scala:200)
while locating play.api.http.JavaCompatibleHttpRequestHandler
while locating play.api.http.HttpRequestHandler
for parameter 4 at play.api.DefaultApplication.<init>(Application.scala:221)
at play.api.DefaultApplication.class(Application.scala:221)
while locating play.api.DefaultApplication
while locating play.api.ApplicationPlay文档建议我使用@ImplementedBy[classOf[RealSystemWrapper]]装饰器,但这给我留下了一个测试问题:如何在测试时将其更改为classOf[MockedSystemWrapper]
发布于 2016-12-15 14:13:55
由于Application依赖于一个特征,因此您需要定义“绑定”(即。使用哪个具体的类)。正如您所描述的,一种方法是@ImplementedBy注释。另一种方法是在模块中定义绑定,如下所述:https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection#Programmatic-bindings
现在,如果您想在测试中使用不同的实例,这取决于您的测试设置。在最简单的情况下,您直接在测试中实例化Application,因此可以手动传入模拟。如果您正在运行您所创建的整个应用程序,那么可以覆盖绑定(如此处所述:https://www.playframework.com/documentation/2.5.x/ScalaTestingWithGuice#Override-bindings)或将已覆盖的模块传递给WithApplication帮助器(如此处所示:https://www.playframework.com/documentation/2.5.x/ScalaFunctionalTestingWithSpecs2)
https://stackoverflow.com/questions/41154466
复制相似问题