Kotlin Mockito always return object passed as an argument

一世执手 提交于 2019-12-24 03:04:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!