mocking only one call at a time with mockk

BadChanneler picture BadChanneler · Sep 14, 2018 · Viewed 9.3k times · Source

I know that in order to mock how a method responds, you have to use

every { instanceX.methodB() } returns "42"

I'm trying to mock an iterator, for which you have to mock 2 methods hasNext() and next(), if hasNext() returns true always there will be an infinite loop, if it returns false from the beginning, next() will not return anything.

My question is: is there a way to mock individual calls one by one with mockk, as you can do in mockito ? I couldn't find anything in the docs.

Answer

p3quod picture p3quod · Apr 27, 2019

At the excellent post Mocking is not rocket science are documented two alternatives:

returnsMany specify a number of values that are used one by one i.e. first matched call returns first element, second returns second element:

    every { mock1.call(5) } returnsMany listOf(1, 2, 3)

You can achieve the same using andThen construct:

    every { mock1.call(5) } returns 1 andThen 2 andThen 3