ps0604
ps0604

Reputation: 1071

Play for Scala: Mock singleton in ScalaTest

I have the following Play Controller class that I need to test with ScalaTest:

class RunFormula @Inject() (dbCache: DbCache) extends Controller  {
    // some code
}

The class DbCache is a singleton:

@Singleton
class DbCache @Inject() (properties: Properties) {
    // some getters and setters
}

And this is the test class:

class RunFormulaTest extends PlaySpec with OneAppPerSuite with MockitoSugar {

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

    @Inject val dbCache : DbCache = null

    val controller = new RunFormula(dbCache)

    // more test code

}

When I run the test, the object dbCache inside RunFormula is null, my understanding was that Guice would create the instance when it's injected but apparently it's not.

Note that the controller RunFormula works correctly with dbCache injected in the non-test scenario.

How to fix the test?

Upvotes: 1

Views: 652

Answers (1)

Tomer
Tomer

Reputation: 2448

You have a couple of ways to do it. First of all, if you want to get the instance of your controller with the database correctly injected you should do something like this:

val app = new GuiceApplicationBuilder().build
val controller = app.injector.instanceOf[RunFormula]

This will get you the instance with your database. You can control the connection of your database in test mode by setting the appropriate properties in your application.conf file.

You can also create an instance of your controller with a database instance you can created by yourself:

val dbUrl = sys.env.getOrElse("DATABASE_URL", "jdbc:postgresql://localhost:5432/yourdatabase?user=username&password=password")
val database = Databases("org.postgresql.Driver", dbUrl,"testingzzz")
val controller = new RunFormula(database)

Upvotes: 1

Related Questions