在我的Module.scala
中,我绑定了一个特征的具体实现,定义如下:
trait AccessGroupRepository[F[_]] {}
@Singleton
class AccessGroupRepositoryImpl @Inject()(db: OldDataBase, c: IOContextShift)
extends AccessGroupRepository[IO] {}
并且绑定是使用 TypeLiteral
完成的:
bind(new TypeLiteral[AccessGroupRepository[IO]] {}).to(classOf[AccessGroupRepositoryImpl])
现在,我需要在使用 Mockito 模拟进行测试时覆盖此绑定:
override val application: Application = guiceApplicationBuilder
.overrides(bind(new TypeLiteral[AccessGroupRepository[IO]] {}).to(agRepoMock))
但我收到以下错误:
overloaded method value bind with alternatives:
[error] [T](implicit evidence$1: scala.reflect.ClassTag[T])play.api.inject.BindingKey[T] <and>
[error] [T](clazz: Class[T])play.api.inject.BindingKey[T]
[error] cannot be applied to (com.google.inject.TypeLiteral[api.v1.accessgroup.AccessGroupRepository[cats.effect.IO]])
[error] .overrides(bind(repoTypeLiteral).to(agRepoMock))
[error] ^
我该如何解决这个问题?
这个问题与如何使用 Scala Guice 将扩展 Trait 的类与 monadic 类型参数绑定有关?
TypeLiteral
在Play Guice API的scala实现中尚不可用。
泛型的当前有效解决方案是创建一个具有所需模拟定义的测试模块,并将其传递到overrides
:
object CustomMockComponentModule extends AbstractModule {
val agRepoMock = ...
@Provides
@Singleton
def mockBean(): AccessGroupRepository[IO] = agRepoMock
}
...
override val application: Application = guiceApplicationBuilder
.overrides(CustomMockComponentModule)
.build()