我有一个uuid生成器,如:
class NewUuid {
def apply: String = UUID.randomUUID().toString.replace("-", "")
}
其他班级可以使用它:
class Dialog {
val newUuid = new NewUuid
def newButtons(): Seq[Button] = Seq(new Button(newUuid()), new Button(newUuid()))
}
现在我要测试Dialog
并模拟newUuid
:
val dialog = new Dialog {
val newUuid = mock[NewUuid]
newUuid.apply returns "uuid1"
}
dialog.newButtons().map(_.text) === Seq("uuid1", "uuid1")
您可以看到返回的uuid始终为uuid1
。
是否可以让newUuid
为不同的通话返回不同的值?例如第一个调用返回uuid1
,第二个调用返回uuid2
,等等
答案 0 :(得分:1)
newUuid.apply returns "uudi1" thenReturns "uuid2"
https://etorreborre.github.io/specs2/guide/SPECS2-3.5/org.specs2.guide.UseMockito.html
答案 1 :(得分:1)
使用迭代器生成UUID
someList
然后提供另一个用于测试:
def newUuid() = UUID.randomUUID().toString.replace("-", "")
val defaultUuidSource = Iterator continually newUuid()
class Dialog(uuids: Iterator[String] = defaultUuidSource) {
def newButtons() = Seq(
Button(uuids.next()),
Button(uuids.next())
)
}