title: Mock Android Firebase Task within Kotlin coroutine
body: <p>I am working with Android project that needs to initialises Firebase token. Mostly working with Kotlin coroutines I would like to implement code line by line, but since there is no way to synchronously request Firebase token I came up with the solution to wrap <code>OnCompleteListener</code> using following function:</p>
  
  <pre><code>private suspend fun fcmCallbackSuspendWrapper(block: (OnCompleteListener&lt;InstanceIdResult&gt;) -&gt; Unit)
          = suspendCancellableCoroutine&lt;Task&lt;InstanceIdResult&gt;&gt; { cont -&gt;
      block(OnCompleteListener { response -&gt;
          cont.resume(response)
      })
  }
  </code></pre>
  
  <p>It basically blocks current thread until callback is called by Task. Then I'm applying said function in my code in following way:</p>
  
  <pre><code>val fcmInstance = fcmCallbackSuspendWrapper { listener -&gt;
      fireBaseInstanceIdProvider
          .provide() // Returns Firebase instance 
          .instanceId // Returns Task&lt;InstanceIdResult&gt;
          .addOnCompleteListener(listener) // Sets listener to block current thread until completed
  }
  </code></pre>
  
  <p>But now I need to add unit test to the code above and here I encounter several problems:</p>
  
  <pre><code>@Mock lateinit var instanceIdResultTaskMock: Task&lt;InstanceIdResult&gt;
  @Mock lateinit var fireBaseInstanceIdProviderMock: Provider&lt;FirebaseInstanceId&gt;
  @Mock lateinit var firebaseInstanceIdMock: FirebaseInstanceId
  
  ...
  
  Mockito.`when`(fireBaseInstanceIdProviderMock.provide()).thenReturn(firebaseInstanceIdMock)
  Mockito.`when`(firebaseInstanceIdMock.instanceId).thenReturn(instanceIdResultTaskMock)
  
  </code></pre>
  
  <p>But since <code>Task&lt;InstanceIdResult&gt;</code> is mocked - it's <code>OnCompleteListener&lt;TResult&gt;</code> is never called and thread is blocked forever, preserving code execution to continue. What can be done in this situation?</p>