Freewind Freewind - 2 months ago 11
Scala Question

How to mock some methods only throw exception for the first time and then do nothing, with specs2?

In specs2, we can mock a method and let it throw exception:

class Hello {
def say():Unit = println("Hello, world")
}

val hello = mock[Hello]
hello.say() throws new RuntimeException("something wrong")


But how to make it just throw the first time, and then always do nothing?

Answer

This is actually a mockito question, not a specs2 one. From the mockito documentation:

when(mock.someMethod("some arg"))
   .thenThrow(new RuntimeException())
   .thenReturn("foo");

Alternative, shorter version of consecutive stubbing:

 when(mock.someMethod("some arg"))
   .thenReturn("one", "two", "three");