Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Mockito always return object passed as an argument

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?

like image 896
Whizzil Avatar asked Aug 18 '19 20:08

Whizzil


People also ask

How do I return the first argument from a method in Mockito?

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:

Can we mock using Mockito in Kotlin?

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.

What is the last argument of a reified method 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:

How to mockfoo Bool() method to return “true”?

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:


Video Answer


1 Answers

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] }
}
like image 166
tynn Avatar answered Nov 11 '22 10:11

tynn