【问题标题】:How to mock a uuid generator which return different values for different calls?如何模拟为不同调用返回不同值的 uuid 生成器?
【发布时间】:2015-11-13 08:53:25
【问题描述】:

我有一个 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,等等

【问题讨论】:

    标签: scala mocking mockito specs2


    【解决方案1】:

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2015-12-02
        • 1970-01-01
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2020-03-23
        • 2022-07-14
        相关资源
        最近更新 更多