Scala,PlayFramework,Mockito,ExecutionContext为null [英] Scala, PlayFramework, Mockito, ExecutionContext null
问题描述
遵循此答案: https://stackoverflow.com/a/30806548/4496364 我在项目中使用Play的ExecutionContext.
Following this answer: https://stackoverflow.com/a/30806548/4496364 I use Play's ExecutionContext in my project.
最近,我需要使用Mockito来测试Play中的某些服务. 因此,这是它的简化版本:
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
}
测试:
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)
}
}
}
}
请注意测试中的注释,在Service
中调用dao.findAll
时会得到一个NullPointException
.起初我以为Mockito无法处理Scala的Futures,但我发现ExecutionContext
是问题所在.由于我不是并发专家,所以有人可以解释为什么会发生这种情况吗?
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?
推荐答案
万一有人在看,答案很明显...
In case someone is looking, the answer was obvious...
import org.mockito.Matchers.any
..
mockDAO.findAll(any[ExecutionContext])
我不熟悉Mockito的工作方式或Scala隐式方法.
如果您不通过any[ExecutionContext]
,Scala会用测试中的隐式填充它.
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.
这篇关于Scala,PlayFramework,Mockito,ExecutionContext为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!