0

I try to achieve something similar to this: How to call a lambda callback with mockk

I pass a mocked service to my real object. How can I get the myService.get callback called? This code gets never called and my test stops at this request.

Here is some sample code:

class MyObject(private val myService: MyService){
    fun getSomeStuff() {
        myService.get(object: MyService.Callback<MyServiceResponse>{
            override fun onResponse(response: MyServiceResponse?) {
                // check response and do some stuff
                // I want to continue my tests here, but this gets never called
            }
        })
    }

How can I create a test that continues inside the callback?

Here is what I trie in my test:

@Test
fun `get some stuff - success`() {
    val myService = mockk<MyService>() {
        every { get(any()) } answers {
            firstArg<() -> MyService.Callback<MyServiceResponse>>().invoke()
        }
    }

    val myObject = MyObject(myService)

    myObject.getSomeStuff()
}
devz
  • 2,629
  • 2
  • 31
  • 37

1 Answers1

1

You should be able to call onResponse() by using:

every { get(any()) } 
answers {
  firstArg<MyService.Callback<MyServiceResponse>>().onResponse(aMyServiceResponse)
}

By the way, as you are using a callback, I guess that the implementation is asynchronous, so you'll probably need to use the coEvery / coAnswer variant.

HTH

  • Sorry for the delay, I moved the code from the `onResponse()`method to a separate method and check this method. I have just found time to test your solution, but I get the following error message in Android Studio: Type mismatch: inferred type is Unit but MockKMatcherScope.DynamicCall was expected – devz Apr 23 '20 at 14:46