Scala 如何模拟为不同调用返回不同值的uuid生成器?

Scala 如何模拟为不同调用返回不同值的uuid生成器?,scala,mocking,mockito,specs2,Scala,Mocking,Mockito,Specs2,我有一个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())) } 现在我想

我有一个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()))
}
现在我想测试
对话框
并模拟
newUuid

val dialog = new Dialog {
    val newUuid = mock[NewUuid]
    newUuid.apply returns "uuid1"
}
dialog.newButtons().map(_.text) === Seq("uuid1", "uuid1")
您可以看到返回的uuid总是
uuid1

是否可以让
newUuid
为不同的调用返回不同的值?e、 g.第一个调用返回
uuid1
,第二个调用返回
uuid2
,以此类推

newUuid.apply returns "uudi1" thenReturns "uuid2"

使用迭代器生成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)