aaverin
08/24/2018, 12:10 PMfun execute(appConfig: AppConfig): Deferred<String> = async {
registerDevice(appConfig.serviceId)
}
private suspend fun registerDevice(serviceId: String): String = suspendCoroutine {
//some nasty 3rd party library delivering data in a callback
lib.registerDeviceForService(object: Callback {
override fun onSuccess(response) {
it.resume(response.data)
}
}
)
}
Here is the test
@Test
fun `ok result of registration results in success`() = blocking {
val deferred = classToTest.execute(appConfig)
mockRegisterResponseSuccess()
val result = deferred.await()
result.should.be.equal(trackingId)
}
To ensure callback is executed, I have to use Mockito ArgumentCaptor:
private fun mockRegisterResponseSuccess(result: ApiResponseStatus) {
then(lib).should().registerDeviceForService(callbackCaptor.capture())
callbackCaptor.firstValue.onSuccess(Response(data = "testdata"))
}
Problem: test function is async and it’s code will be executed only after await() called
that means that I can not capture the callback and mock it’s execution
Any ideas?