【发布时间】:2018-04-18 10:55:46
【问题描述】:
我正在测试一个执行一些异步计算的服务实现。这是特点
trait Event
trait Service{
def processEvents(ex: Seq[Event])
}
我有以下实现:
//Business logic
trait EventHandler{
def handleEvent(e: Event)
}
//Threading
class AsynchronousService(private final val handler: EventHandler)
extends Service {
def processEvents(ex: Seq[Event]) = {
//execute handler.handleEvent(e) in some
//thread pool or so...
//should not do any processing in case of ex.isEmpty
}
}
我遇到的问题是在测试AsynchronousService 是否为空Seq[Event] 时。这是我在 scalatest 中的测试:
it("should verify no processing in case of empty event seq"){
val mockedHandler = //mock with Mockito
val service = new AsynchronousService(mockedHandler)
service.processEvents(Seq())
Thread.sleep(1000) //<--- waiting some time. looks ugly
verifyZeroInteraction(mockedHandler)
}
问题在于Thread.sleep(1000)。只要AsynchronousService 对另一个线程执行调度/提交/或其他操作,不等待一段时间就得出结论然后执行verifyZeroInteraction(mockedHandler) 是不正确的。但是Thread.sleep(1000) 看起来很奇怪。
问题:可能有Scalatest 设施吗?或者如何正确编写这样的测试?
【问题讨论】:
标签: scala testing mockito scalatest