Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocking only one call at a time with mockk

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.

like image 708
BadChanneler Avatar asked Sep 14 '18 05:09

BadChanneler


People also ask

What is MockK relaxed?

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.

What is Spy in MockK?

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.

What is mockkStatic?

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.


2 Answers

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 
like image 173
p3quod Avatar answered Sep 17 '22 19:09

p3quod


Use returnsMany or andThen construct with/instead of return.

like image 31
oleksiyp Avatar answered Sep 18 '22 19:09

oleksiyp