Kotlin Mockito always return object passed as an argument

Whizzil :

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?

tynn :

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] }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145354&siteId=1