3

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?

Community
  • 1
  • 1
insan-e
  • 3,883
  • 3
  • 18
  • 43
  • Maybe it could an issue not with ExecutionContext, but with `trait`?http://stackoverflow.com/questions/6243467/scala-and-mockito-with-traits?rq=1 – Artur Zagretdinov May 01 '16 at 22:47

1 Answers1

4

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.

insan-e
  • 3,883
  • 3
  • 18
  • 43