title: Testing coroutines in Kotlin
body: <p>I have this simple test about a crawler that is supposed to call the repo 40 times:</p>
  
  <pre><code>@Test
  fun testX() {
     // ... 
     runBlocking {
          crawlYelp.concurrentCrawl()
          // Thread.sleep(5000) // works if I un-comment
     }
     verify(restaurantsRepository, times(40)).saveAll(restaurants)
     // ...
  }
  </code></pre>
  
  <p>and this implementation:</p>
  
  <pre><code>suspend fun concurrentCrawl() {
      cities.map { loc -&gt;
          1.rangeTo(10).map { start -&gt;
              GlobalScope.async {
                  val rests = scrapYelp.scrap(loc, start * 10)
                  restaurantsRepository.saveAll(rests)
              }
          }
      }
  }
  </code></pre>
  
  <p>But... I get this:</p>
  
  <pre><code>Wanted 40 times:
  -&gt; at ....testConcurrentCrawl(CrawlYelpTest.kt:46)
  But was 30 times:
  </code></pre>
  
  <p>(the 30 is changing all the time; so it seems the test is not waiting...)</p>
  
  <p>Why does it pass when I do the sleep? It should not be needed given I run blocking..</p>
  
  <p>BTW, I have a controller that is supposed to be kept asynchronous:</p>
  
  <pre><code>@PostMapping("crawl")
  suspend fun crawl(): String {
      crawlYelp.concurrentCrawl()
      return "crawling" // this is supposed to be returned right away
  }
  </code></pre>
  
  <p>Thanks</p>