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.
A relaxed mock is the mock that returns some simple value for all functions. This allows you to skip specifying behavior for each case, while still stubbing things you need. For reference types, chained mocks are returned. Note: relaxed mocking is working badly with generic return types.
Both can be used to mock methods or fields. The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it. When using mock objects, the default behavior of the method when not stub is do nothing.
mockkStatic("com.name.app.Writer") Rather than passing a reference to the class, you pass the class name as a string. You can also choose to pass in a reference to the class, and MockK will figure out the class name. mockkStatic(Writer::class) Like object mocks, static mocks behave like spies.
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
Use returnsMany
or andThen
construct with/instead of return
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With