【发布时间】:2019-08-23 04:43:23
【问题描述】:
我有一个关于应该调用 repo 40 次的爬虫的简单测试:
@Test
fun testX() {
// ...
runBlocking {
crawlYelp.concurrentCrawl()
// Thread.sleep(5000) // works if I un-comment
}
verify(restaurantsRepository, times(40)).saveAll(restaurants)
// ...
}
还有这个实现:
suspend fun concurrentCrawl() {
cities.map { loc ->
1.rangeTo(10).map { start ->
GlobalScope.async {
val rests = scrapYelp.scrap(loc, start * 10)
restaurantsRepository.saveAll(rests)
}
}
}
}
但是...我明白了:
Wanted 40 times:
-> at ....testConcurrentCrawl(CrawlYelpTest.kt:46)
But was 30 times:
(30一直在变化;所以看起来测试没有等待......)
为什么我睡觉时它会过去?考虑到我运行阻塞,它不应该是必需的..
顺便说一句,我有一个应该保持异步的控制器:
@PostMapping("crawl")
suspend fun crawl(): String {
crawlYelp.concurrentCrawl()
return "crawling" // this is supposed to be returned right away
}
谢谢
【问题讨论】:
标签: kotlin junit kotlin-coroutines