14

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?

Whizzil
  • 1,264
  • 6
  • 22
  • 39
  • Do you create and pass the `user` in the test code ? Or it's created somewhere else in the code under test ? – Arnaud Claudel Aug 18 '19 at 20:36
  • @ArnaudClaudel I create and pass it in the test code. But the setup line is not in the actual test, it's before, on the top of the test class, before any test. – Whizzil Aug 18 '19 at 20:47
  • Then add a line in the test that return the specific instance when insert() is called. I don't think that it's a bad design – Arnaud Claudel Aug 18 '19 at 20:53
  • @ArnaudClaudel This is not what I want, and especially doesn't answer my question. – Whizzil Aug 18 '19 at 20:59
  • Wait. Why are you using Mockito to tell what a MockK mock should do? Use MockK, or use Mockito. Don't mix both. – JB Nizet Aug 18 '19 at 21:25
  • @JBNizet Any example how to do that with Mockk? – Whizzil Aug 18 '19 at 21:28
  • `private val dal = mockk { every { insert(any()) } returnsArgument 0 }`. But do you understand that it makes no sense to use Mockito to tell what a MockK mock should do? These are different mocking frameworks. Choose one, and read its documentation. MockK is a better choice for Kotlin, IMHO – JB Nizet Aug 18 '19 at 21:29
  • @JBNizet I do understand, but I didn't find a way to do it with Mockk. And I can't resolve this method `returnsArgument`, where does it come from? Hm probably newer version. I'm on 1.8 – Whizzil Aug 18 '19 at 21:36
  • 1
    From the public API of MockK (I use it in version 1.9.1). See https://github.com/mockk/mockk/blob/2244688efc2439eb0a67fec595e26ab53f2ee324/dsl/common/src/main/kotlin/io/mockk/API.kt#L2143-L2144. – JB Nizet Aug 18 '19 at 21:41

1 Answers1

33

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] }
}
tynn
  • 38,113
  • 8
  • 108
  • 143