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
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.
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.
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.
Following oleksiyp comment, I reread the docs. Correct way is:
val captureMyObject = slot<MyObject>()
every { serviceX.doSomething(capture(captureMyObject)) } answers {captureMyObject.captured}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With