title: mock retrofit suspend function infinite response
body: <p>I would like to test case when server does not return response, and we trigger the next network call ( like for example search query).</p>
  
  <p>So we basically have a method inside ViewModel and Retrofit method</p>
  
  <pre><code>  interface RetrofitApi {
      @GET("Some Url")
      suspend fun getVeryImportantStuff(): String
  }
  
  class TestViewModel(private val api: RetrofitApi) : ViewModel() {
  
      private var askJob: Job? = null
      fun load(query: String) {
          askJob?.cancel()
          askJob = viewModelScope.launch {
              val response = api.getVeryImportantStuff()
  
              //DO SOMETHING WITH RESPONSE
  
          }
      }
  }
  </code></pre>
  
  <p>And I would like to test case when new query is asked, and the old one didn't returns.
  for case when response returns test is easy</p>
  
  <pre><code>@Test
      fun testReturnResponse() {
          runBlockingTest {
              //given
              val mockApi:RetrofitApi = mock()
              val viewModel = TestViewModel(mockApi)
              val response = "response from api"
  
              val query = "fancy query"
              whenever(mockApi.getVeryImportantStuff()).thenReturn(response)
  
              //when
              viewModel.load(query)
  
  
              //then
              //verify what happens
          }
      }
  </code></pre>
  
  <p>But I don't know how to mock suspend function that did't come back, and test case when new request is triggered like this</p>
  
  <pre><code>@Test
      fun test2Loads() {
          runBlockingTest {
              //given
              val mockApi:RetrofitApi = mock()
              val viewModel = TestViewModel(mockApi)
              val response = "response from api"
              val secondResponse = "response from api2"
  
              val query = "fancy query"
              whenever(mockApi.getVeryImportantStuff())
                  .thenReturn(/* Here return some fancy stuff that is suspend* or something like onBlocking{} stub but not  blocking but dalayed forever/)
                  .thenReturn(secondResponse)
  
              //when
              viewModel.load(query)
              viewModel.load(query)
  
  
              //then
              //verify that first response did not happens , and only second one triggered all the stuff
          }
      }
  </code></pre>
  
  <p>Any ideas ? </p>
  
  <p>EDIT: I'm not really attached to mockito, any mock library will be good :)
  regards
  Wojtek</p>