如何模拟一个 uuid 生成器,它 return 不同的调用有不同的值?
How to mock a uuid generator which return different values for different calls?
我有一个 uuid 生成器,例如:
class NewUuid {
def apply: String = UUID.randomUUID().toString.replace("-", "")
}
其他class可以使用:
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")
您可以看到 returned uuid 始终是 uuid1
。
是否可以让newUuid
到return不同的调用取不同的值?例如第一次调用 returns uuid1
,第二次调用 returns uuid2
,等等
newUuid.apply returns "uudi1" thenReturns "uuid2"
https://etorreborre.github.io/specs2/guide/SPECS2-3.5/org.specs2.guide.UseMockito.html
使用迭代器生成您的 UUID
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())
)
}
然后提供一个不同的测试:
val testUuidSource = Iterator from 1 map {"uuid" + _}
new Dialog(testUuidSource)
我有一个 uuid 生成器,例如:
class NewUuid {
def apply: String = UUID.randomUUID().toString.replace("-", "")
}
其他class可以使用:
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")
您可以看到 returned uuid 始终是 uuid1
。
是否可以让newUuid
到return不同的调用取不同的值?例如第一次调用 returns uuid1
,第二次调用 returns uuid2
,等等
newUuid.apply returns "uudi1" thenReturns "uuid2"
https://etorreborre.github.io/specs2/guide/SPECS2-3.5/org.specs2.guide.UseMockito.html
使用迭代器生成您的 UUID
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())
)
}
然后提供一个不同的测试:
val testUuidSource = Iterator from 1 map {"uuid" + _}
new Dialog(testUuidSource)