如何在单元测试中让runBlocking等待“所有线程”?

时间:2019-04-19 22:33:37

标签: mockito kotlin-coroutines

我正在尝试为getUser()函数编写单元测试:

fun getUser(userId:Int) {
    // some code...

    launchDataOperation { api.getUser(userId) }
}

我可以看到的问题(但不知道如何解决)是launchDataOperation(...)创建一个协程来调用暂停函数api.getUser

fun launchDataOperation(block: suspend () -> Unit): Job {
    return coroutineScope.launch {
        try {
            setLoading(true)
            block()
        } catch (error: NetworkConnectionException) {
            setError(Errors.NETWORK_CONNECTION_ERROR)
        } catch (error: DataOperationException) {
            setMessage(error.getErrors())
        } finally {
            setLoading(false)
        }
    }
}

这是我的考试不及格:

@Test
fun `error message is displayed if api error occurred`() {
    val exception = DataOperationException(listOf("FATAL ERROR"))

    runBlocking {
        `when`(api.getUser(anyInt())).thenAnswer { throw exception }

        subject.getUser(userId)

        // execution fails if the below line is commented
        // this is not the correct way to wait for other coroutines
        delay(500)  // wait for 500ms till the other coroutines finish

        assertThat(subject.messages.value).isEqualTo(exception.getErrors())
    }
}

0 个答案:

没有答案