问题
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?
回答1:
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] }
}
来源:https://stackoverflow.com/questions/57548165/kotlin-mockito-always-return-object-passed-as-an-argument