【发布时间】:2017-12-21 01:15:44
【问题描述】:
我正在尝试测试
trait Name extends Helper {
def name() = {
var s = getSystem()
s.name()
}
}
我要做的就是确保“s.name()”方法被调用一次,方法是模拟一个 s 的实例,它是一个系统。
Helper 是这样定义的:
trait Helper {
def getSystem() : System = {
systemGetter.get()
}
}
到目前为止,我的 NameSpec 看起来像:
class NameSpec extends FlatSpec with Matchers with MockitoSugar {
class NameImpl extends Name
var toTest = new NameImpl
val mockSystem = mock[System]
it should "call s.name() once" in {
when(getSystem() is invoked, return a mockSystem)
toTest.name()
// Verify that mockSystem.name() happened only once
}
}
我感到困惑的是如何在 toTest.name() 调用 getSystem() 时返回一个模拟 System,以便我可以验证系统只调用 s.name() 一次。如果它是 Name trait 中的 name() 方法的参数,我可以轻松地模拟这个 System,所以我想我不知道如何在调用该方法时“注入”要使用的 mockSystem 而不是真实系统。
【问题讨论】:
标签: scala mockito traits scalatest