Scala - Play - 如何在测试中模拟导入 play.api.libs.concurrent.CustomExe



我有一个测试,它正在测试一个需要隐式CustomExecutionContext的类:

@Singleton
class MyRepo @Inject()
(appConfigService: AppConfigService)
(implicit ec: RepositoryDispatcherContext)

现在我需要测试这个类,并在测试期间注入一个模拟调度程序上下文。最初,我考虑使用开箱即用的标准全局执行上下文。

implicit executionContext = scala.concurrent.ExecutionContext.Implicits.global

但是测试失败了,它需要另一种类型的实例:

找不到参数 ec 的隐式值: common.executor.RepositoryDispatcherContext

这是我的自定义执行上下文:

import javax.inject.{Inject}
import akka.actor.ActorSystem
import play.api.libs.concurrent.CustomExecutionContext
class RepositoryDispatcherContext @Inject()(actorSystem: ActorSystem) extends CustomExecutionContext(actorSystem, "repository.dispatcher")

想知道如何注入我的自定义执行上下文的模拟实例以用作我的 Test 类中的隐式参数?

您可以创建自定义调度程序的子类并覆盖必要的方法:

import org.specs2.mutable.Specification
import akka.actor.ActorSystem
import scala.concurrent.ExecutionContext
class MySomethingSpec extends Specification with Mockito {
"MySomething" should {    
"mock repository dispatcher itself" in {
class MyMockedRepositoryDispatcher(executionContext: ExecutionContext) extends RepositoryDispatcherContext(ActorSystem()) {
override def execute(command: Runnable) = executionContext.execute(command)
override def reportFailure(cause: Throwable) = executionContext.reportFailure(cause)
}
val executionContext: ExecutionContext = ??? // whatever you need
val repositoryDispatcher: RepositoryDispatcherContext = new MyMockedRepositoryDispatcher(executionContext)
// do what you need
// assertions
}
}
}

最新更新