[英]How to mock a uuid generator which return different values for different calls?
I have a uuid generator, like: 我有一个uuid生成器,例如:
class NewUuid {
def apply: String = UUID.randomUUID().toString.replace("-", "")
}
And other class can use it: 其他类可以使用它:
class Dialog {
val newUuid = new NewUuid
def newButtons(): Seq[Button] = Seq(new Button(newUuid()), new Button(newUuid()))
}
Now I want to test the Dialog
and mock the newUuid
: 现在,我想测试
Dialog
并模拟newUuid
:
val dialog = new Dialog {
val newUuid = mock[NewUuid]
newUuid.apply returns "uuid1"
}
dialog.newButtons().map(_.text) === Seq("uuid1", "uuid1")
You can see the returned uuid is always uuid1
. 您可以看到返回的uuid始终为
uuid1
。
Is it possible to let newUuid
to return different values for different calls? 是否可以让
newUuid
为不同的调用返回不同的值? eg The first call returns uuid1
, the second returns uuid2
, etc 例如,第一个调用返回
uuid1
,第二个返回uuid2
, uuid2
newUuid.apply returns "uudi1" thenReturns "uuid2"
https://etorreborre.github.io/specs2/guide/SPECS2-3.5/org.specs2.guide.UseMockito.html
Use an iterator to produce your UUIDs 使用迭代器生成您的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())
)
}
Then provide a different one for testing: 然后提供另一种进行测试:
val testUuidSource = Iterator from 1 map {"uuid" + _}
new Dialog(testUuidSource)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.