Search code examples
scalamockingmockitospecs2

How to mock a uuid generator which return different values for different calls?


I have a uuid generator, like:

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:

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.

Is it possible to let newUuid to return different values for different calls? e.g. The first call returns uuid1, the second returns uuid2, etc


Solution

  • newUuid.apply returns "uudi1" thenReturns "uuid2"
    

    https://etorreborre.github.io/specs2/guide/SPECS2-3.5/org.specs2.guide.UseMockito.html