Some of my controllers rely on a database connection and are structured as follows:
def getAll(revId: Muid) = Action { implicit request =>
DB.withConnection { implicit connection =>
...
I am trying to create a unit test for it with all the mocked dependencies, including the connection. Dependency injection is now easy to do through Guice. However, I am struggling to find a way to mock the implicit join. And finally, the test tries to connect to my default database in the test.
Is it even possible to ridicule the implication, given this situation, and how?
UPDATE
So, after playing with this thing for a while I got the following: Test of my class:
class ChecklistCreationScheduler @Inject()(jobScheduler: JobScheduler,
dBApi: DBApi,
futureChecklistRepository: FutureChecklistRepository) extends ClassLogger{
def scheduleSingleFutureChecklistJob(futureChecklistId: Muid): Unit = {
logger.info(s"Preparing to schedule one time future checklist job for future checklist id '${futureChecklistId.uuid}'")
val db = dBApi.database("default")
logger.info("Database" + db)
db.withConnection { implicit connection =>
logger.info("Connection" + connection)
...
}
}
}
And the test:
"ChecklistCreationScheduler#scheduleSingleFutureChecklistJob" should {
"schedule a single job through a scheduler" in {
val futureChecklistId = Muid.random()
val jobScheduler = mock[JobScheduler]
val connection = mock[Connection]
val DB = mock[Database]
DB.getConnection returns connection
val dbApi = mock[DBApi]
when(dbApi.database("default")).thenReturn(DB)
val futureChecklistRepository = mock[FutureChecklistRepository]
doReturn(Option.empty).when(futureChecklistRepository).getById(futureChecklistId)(connection)
val chCreationScheduler = new ChecklistCreationScheduler(jobScheduler, dbApi, futureChecklistRepository)
chCreationScheduler.scheduleSingleFutureChecklistJob(futureChecklistId) must throwA[UnexpectedException]
}
}
When I execute the test, it seems that the execution does not even fall into the block withConnection. (I never get to this line :) logger.info("Connection" + connection).
Any idea?