Search code examples
scalaunit-testingplayframeworkmockingexecutioncontext

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:

@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

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?


Solution

  • 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
        }
      }
    }