insan-e
insan-e

Reputation: 3921

Scala, PlayFramework, Mockito, ExecutionContext null

Following this answer: https://stackoverflow.com/a/30806548/4496364 I use Play's ExecutionContext in my project.

Recently I needed to use Mockito to test some services in Play. So, this is simplified version of it:

import scala.concurrent.{ Future, ExecutionContext }
import play.api.libs.concurrent.Execution.Implicits.defaultContext

case class Model(id: Int, name: String)

trait DAO {
  def findAll(implicit ec: ExecutionContext): Future[List[Model]]
}

class Service(dao: DAO) {
  def findAll: Future[List[Model]] = dao.findAll
}

Test:

import play.api.libs.concurrent.Execution.Implicits.defaultContext
// doesn't work when different ExecutionContext
// import scala.concurrent.ExecutionContext.Implicits.global


class FuturesTest extends PlaySpec with MockitoSugar with ScalaFutures {

  "Service" should {
    "return all future data" in {
      val mockModel = Model(1, "name")
      val mockDAO = mock[DAO]
      when(mockDAO.findAll) thenReturn Future.successful(List(mockModel))

      val service = new Service(mockDAO)
      val futureData = service.findAll
      whenReady(futureData) { data =>
        data.map(_.name) must contain(mockModel.name)
      }
    }
  }

}

Note the comment in test, i get a NullPointException when calling dao.findAll in the Service. At first I thought that Mockito can't handle Scala's Futures but I figured out that the ExecutionContext is the problem. Since I'm not a concurrency expert, can someone please explain why does this happen?

Upvotes: 3

Views: 1470

Answers (1)

insan-e
insan-e

Reputation: 3921

In case someone is looking, the answer was obvious...

import org.mockito.Matchers.any
..
mockDAO.findAll(any[ExecutionContext])

I wasn't familiar with how Mockito works, or with Scala implicits. When you don't pass any[ExecutionContext] Scala will fill it with the implicit one from the test.

Upvotes: 4

Related Questions