[英]Scala - Play - How to mock import play.api.libs.concurrent.CustomExecutionContext in Test and use it as an implicit param?
I have a test which is testing a class that expects an implicit CustomExecutionContext: 我有一个测试正在测试期望隐式CustomExecutionContext的类:
@Singleton
class MyRepo @Inject()
(appConfigService: AppConfigService)
(implicit ec: RepositoryDispatcherContext)
Now I need to test this class and inject a mock dispatcher context during test. 现在,我需要测试该类,并在测试过程中注入模拟调度程序上下文。 Initially I was thinking of using the standard global execution context that ships out of the box.
最初,我考虑使用现成的标准全局执行上下文。
implicit executionContext = scala.concurrent.ExecutionContext.Implicits.global
But the test fails at it expects another type of instance: 但是由于期望其他类型的实例而导致测试失败:
could not find implicit value for parameter ec: common.executor.RepositoryDispatcherContext
找不到参数ec的隐式值:common.executor.RepositoryDispatcherContext
This is mine Custom execution context: 这是我的自定义执行上下文:
import javax.inject.{Inject}
import akka.actor.ActorSystem
import play.api.libs.concurrent.CustomExecutionContext
class RepositoryDispatcherContext @Inject()(actorSystem: ActorSystem) extends CustomExecutionContext(actorSystem, "repository.dispatcher")
Was wondering how to inject a mock instance of my custom execution context to be used as an implicit param in my Test class? 想知道如何将自定义执行上下文的模拟实例用作Test类中的隐式参数吗?
You can create a sub class of your custom dispatcher and override the necessary methods: 您可以创建自定义调度程序的子类,并覆盖必要的方法:
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.