当使用kotlin协同程序时,如何对一个调用暂停function的函数进行unit testing?
我有这样的课
class SomeClass { fun someFun() { // ... Some synchronous code async { suspendfun() } } private suspend fun suspendFun() { dependency.otherFun().await() // ... other code } }
我想unit testingsomeFun()
所以我写了一个unit testing,看起来像这样:
@Test fun testSomeFun() { runBlocking { someClass.someFun() } // ... verifies & asserts }
但是,这似乎不工作,因为runBlocking实际上并没有阻止执行,直到runBlocking内的一切完成。 如果我直接在runBlocking
里面测试suspendFun()
它可以像预期的那样工作,但是我想能够一起测试someFun()
。
任何线索如何测试同步和异步代码的function?
修复异步
正如所实施的,你的someFun()
将只是“发射并忘记” async
结果。 因此, runBlocking
在这个测试中并没有什么不同。
如果可能,使someFun()
返回async
的Deferred
,然后在runBlocking
中调用await
。
fun someFun(): Deferred { // ... Some synchronous code return async { suspendFun() } }
然后测试:
runBlocking { SomeClass().someFun().await() }
这个问题/答案是进一步信息的一个很好的资源。
替代方法:使用启动
也可以避免使用suspend
function和launch
创建的协同程序的async
:
suspend fun someFun() { // ... Some synchronous code suspendFun() } private suspend fun suspendFun() { delay(1000) println("executed") // ... other code }
测试使用launch
并使用join
等待其执行:
runBlocking { launch { SomeClass().someFun() }.join() }