我正在使用Scalatest和Slick 3.1.1,我想模拟数据库以便能够返回我需要的内容。我试过Scalamock。它甚至没有编译。我已经尝试了Mockito。它编译,但mock总是返回null而不是指定的Future。据我所知,它与匹配器和泛型有关,但我不知道如何解决它。这是我尝试过的:
// action what I need to execute
def findById(id: UUID): DBIOAction[Option[TaskResult], NoStream, Read] =
taskResultTable.filter(_.taskId === id).result.headOption
// mock with generics specified explicitly
val mockedDb = Mockito.mock(classOf[Database])
Mockito.when(mockedDb.run(Matchers.any[DBIOAction[Option[TaskResult], NoStream, Read]]()))
.thenReturn(Future.failed(new Exception))
val f = mockedDb.run(findById(UUID.randomUUID()))
println(f)
// f is null
// mock without explicit generics
val mockedDb = Mockito.mock(classOf[Database])
Mockito.when(mockedDb.run(Matchers.any()))
.thenReturn(Future.failed(new Exception))
val f = mockedDb.run(findById(UUID.randomUUID()))
println(f)
// f is null
// mock with exact action
val mockedDb = Mockito.mock(classOf[Database])
val action = findByIds(Seq(UUID.randomUUID()))
Mockito.when(mockedDb.run(action))
.thenReturn(Future.failed(new Exception))
val futureFromSpecifiedAction = mockedDb.run(action)
println(futureFromSpecifiedAction)
// futureFromSpecifiedAction is not null and what I need
val differentAction = findByIds(Seq(UUID.randomUUID()))
val futureFromDifferentAction = mockedDb.run(differentAction)
println(futureFromDifferentAction)
// futureFromDifferentAction is null
如果我指定完全相同的动作将被传递给运行,我只会取得成功,显然它无法在测试中实现。 我在这里做错了什么?