I am trying to use Mockito on my mocked object in such a way that it should always return the very same object that was passed in as an argument. I tried it do to it like so:
private val dal = mockk<UserDal> {
Mockito.`when`(insert(any())).thenAnswer { doAnswer { i -> i.arguments[0] } }
}
However, this line always fails with:
io.mockk.MockKException: no answer found for: UserDal(#1).insert(null)
The insert(user: User)
method doesn't take in null
as an argument (obviously User
is not a nullable type).
How can I make the insert()
method always return the same object that it received as an argument?
Returning the First Argument Mockito provides built-in support for getting method arguments. Hence we'll be using the AdditionalAnswers class which contains different implementations of the Answer interface. Firstly, AdditionalAnswers.returnsFirstArg () helps us returning the first argument:
Introduction Kotlin and Java walk hand in hand. This means we can leverage the vast number of existent Java libraries in our Kotlin projects. In this short article, we’ll see how we can mock using Mockito in Kotlin.
As we can see, it's reified method - type returned by that method will be inferred in proper context, so without passing extra type information we can write: Last argument of that method is stubbing: KStubbing<T>. (T)->Unit. In Kotlin, last functional argument of method could be reduced to just opening lambda in declaration:
Foo mockFoo = mock (Foo.class); when (mockFoo.bool (anyString (), anyInt (), any (Object.class))).thenReturn (true); We are stubbing bool () method to return “true” for any string, integer and object arguments. All the below assertions will pass in this case:
When you're using MockK you should not use Mockito.
Only using MockK you can achieve the same with:
val dal = mockk<UserDal> {
every { insert(any()) } returnsArgument 0
}
If you intend to use Mockito, you should remove MockK and use mockito-kotlin:
val dal = mock<UserDal> {
on { insert(any()) } doAnswer { it.arguments[0] }
}
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