【发布时间】:2021-07-22 04:35:04
【问题描述】:
我正在为我的代码的一些异步部分(返回 Futures)编写单元测试,这也涉及到模拟 Scala 对象的需要。
在these docs 之后,我可以成功地模拟对象的功能。我的问题源于withObjectMocked[FooObject.type] 返回Unit 的事实,其中scalatest 中的异步测试需要返回Assertion 或Future[Assertion]。为了解决这个问题,我在我的测试中创建了vars,我在发送到withObjectMocked[FooObject.type] 的函数中重新分配它,最终看起来像这样:
class SomeTest extends AsyncWordSpec with Matchers with AsyncMockitoSugar with ResetMocksAfterEachAsyncTest {
"wish i didn't need a temp var" in {
var ret: Future[Assertion] = Future.failed(new Exception("this should be something")) // <-- note the need to create the temp var
withObjectMocked[SomeObject.type] {
when(SomeObject.someFunction(any)) thenReturn Left(Error("not found"))
val mockDependency = mock[SomeDependency]
val testClass = ClassBeingTested(mockDependency)
ret = testClass.giveMeAFuture("test_id") map { r =>
r should equal(Error("not found"))
} // <-- set the real Future[Assertion] value here
}
ret // <-- finally, explicitly return the Future
}
}
然后我的问题是,是否有更好/更清洁/更惯用的方法来编写模拟对象的异步测试,而无需跳过这一点?出于某种原因,我认为使用AsyncMockitoSugar 而不是MockitoSugar 会为我解决这个问题,但withObjectMocked 仍然返回Unit。这可能是一个错误和/或功能请求的候选(withObjectMocked 的异步版本返回功能块的值而不是Unit)?还是我错过了如何完成此类任务?
【问题讨论】:
标签: asynchronous scalatest mockito-scala