Title
i

igorvd

05/14/2019, 7:36 PM
Is there an way to mock a function that receives a callback as parameter? For example, assuming that I have an assync operation, and the way to get the result is using an interface as callback. I want to unit test this method, defining responses in this callback. The problem lies in the fact that the callback is declared as anonymous (I will put an example below). Is possible to mock this callback and define its responses using MockK? Here is an example:
class ViewModel {

	fun loadSomeStuff() {
		myObject.asyncOperation(object : Callback {
			//callback methods implementation
		})
	}
}
I know if I change the callback for a parameter in my class, it will be easily mocked. But, in my opinion it doesn't make sense, because it's related to the operation I need in the method. (This example is just for learning purposes, I was trying to teach a colleague about unit tests, and I got stocked in this scenario)
h

Hadi Tok

05/14/2019, 10:04 PM
If I understand correctly you can check this blog post https://blog.kotlin-academy.com/mocking-is-not-rocket-science-mockk-features-e5d55d735a98
👎 1
specifically
every { spy.magnify(any()) } answers { firstArg<Int>() * 2 }
this line
with
answers
and
firstArg
you will be able to access first arguement of a mocked function. with this you can do whatever you need
👍 3
i

igorvd

05/15/2019, 5:46 PM
Thanks. I'll try it