Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture an argument that was passed to a mocked function and return it?

Tags:

kotlin

mockk

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

like image 470
BadChanneler Avatar asked May 12 '19 03:05

BadChanneler


People also ask

What is argument capture?

ArgumentCaptor allows us to capture an argument passed to a method to inspect it. This is especially useful when we can't access the argument outside of the method we'd like to test.

How do you use mock method in arguments?

Mockito mock() method It is used to create mock objects of a given class or interface. Mockito contains five mock() methods with different arguments. When we didn't assign anything to mocks, they will return default values. All five methods perform the same function of mocking the objects.

What is @captor in Java?

Mockito ArgumentCaptor is used to capture arguments for mocked methods. ArgumentCaptor is used with Mockito verify() methods to get the arguments passed when any method is called. This way, we can provide additional JUnit assertions for our tests.


1 Answers

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

val captureMyObject = slot<MyObject>()
every { serviceX.doSomething(capture(captureMyObject)) } answers {captureMyObject.captured}
like image 138
BadChanneler Avatar answered Oct 18 '22 07:10

BadChanneler