Search code examples
scalaplayframeworkplayframework-2.0scalatest

Disable singleton when testing with ScalaTest in Play for Scala


I have the following @Singleton in my Play for Scala application that loads on startup:

@Singleton
class Scheduler @Inject()(@Named("mainEtl") mainEtl: ActorRef, system: ActorSystem) {

// some code  
}

This is the module where Scheduler is declared. The module is enabled in application.conf:

class Module extends AbstractModule {
  def configure() = {
    bind(classOf[Scheduler]).asEagerSingleton
  }
}

And the related module definition to configure the @Named injected object, also declared in application.conf:

class AkkaBindings extends AbstractModule with AkkaGuiceSupport {
   def configure = {
     bindActor[MainEtl]("mainEtl")
  }
}

When I run any ScalaTest test, apparently the singleton starts running because I get an error saying that it doesn't find MainEtl (the object injected in the Scheduler class). The point is that I don't need to run the singleton for my tests, so I need to disable it.

This is how I invoke the Play application in my tests:

class ManageBanksTest extends PlaySpec with OneAppPerSuite with MockitoSugar {

  implicit override lazy val app = new GuiceApplicationBuilder().build

   // more test code  
}

This is how I tried to disable it, but it doesn't work as I get the same error:

  implicit override lazy val app = new GuiceApplicationBuilder()
    .disable[Scheduler]
    .build

Alternatively, I could mock Scheduler, but I would have to mock also the @Named injected object and I couldn't find information on how to achieve that.

Any ideas?


Solution

  • This is the solution: to disable the Module class not to declare Scheduler as singleton:

    implicit override lazy val app = new GuiceApplicationBuilder()
        .disable[Module]
        .build