18

So in the service I am testing, I have a depending service which is taking an object and does some augmenting on it. I want to mock the part the depending service is doing and make the mock return exactly what it's receiving. Problem is I don't have access to that.

I tried something like this:

  val captureMyObject = slot<MyObject>()
  every { serviceX.doSomething(capture(captureMyObject)) } 
  returns captureMyObject.captured

But it fails with: kotlin.UninitializedPropertyAccessException: lateinit property captured has not been initialized

BadChanneler
  • 1,450
  • 1
  • 12
  • 20

1 Answers1

36

Following oleksiyp comment, I reread the docs. Correct way is:

val captureMyObject = slot<MyObject>()
every { serviceX.doSomething(capture(captureMyObject)) } answers {captureMyObject.captured}
BadChanneler
  • 1,450
  • 1
  • 12
  • 20
  • 2
    Thanks for taking the time to answer your question. You solved my problem. You should accept your answer. – Ellen Spertus Mar 27 '20 at 19:52
  • 3
    Came across this one I had similar error. I just want to point out that if you have code that throws an exception the the method you expect to be called is never called, that is nothing is captured, they you will also get the same error. – sheu Sep 16 '21 at 16:01
  • @sheu not worth mentioning because what you said is implementation-dependent – Farid Nov 29 '21 at 12:05
  • 1
    @sheu your comment prevented me to go in the wrong direction :), thanks – Russell Ghana Jan 28 '22 at 08:46
  • Still, get the error if I use `throws` instead of `answers`. which is an answer! – Dr.jacky Jul 24 '23 at 08:28