【问题标题】:How to override a TypeLiteral in Scala Guice when testing测试时如何在 Scala Guice 中覆盖 TypeLiteral
【发布时间】:2019-06-20 17:48:49
【问题描述】:

在我的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]                ^

我该如何解决?

这个问题与How to bind a class that extends a Trait with a monadic type parameter using Scala Guice?有关

【问题讨论】:

  • 你有测试模块吗?你能展示一下吗?认为这个问题和下面标记的答案可以帮助stackoverflow.com/questions/483087/overriding-binding-in-guice/…
  • 很遗憾,我没有测试模块,但基本上我需要找到一种方法来做一个.overrides(bind(new TypeLiteral[REPO[IO]] {}).to(MOCK))
  • 我对 Play 和 scale 不熟悉,但是你需要将 override 放在 test moudle 中,并做与 Guice.createInjector(Modules.override(new ProductionModule()).with(new TestModule()));

标签: scala playframework guice


【解决方案1】:

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()   

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多