简体   繁体   English

如何模拟一个uuid生成器,该生成器针对不同的调用返回不同的值?

[英]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 ,第二个返回uuid2uuid2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM