Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何使用回调参数为异步函数编写单元测试_Unit Testing_Testing_Kotlin_Ktor_Kotlin Multiplatform - Fatal编程技术网

Unit testing 如何使用回调参数为异步函数编写单元测试

Unit testing 如何使用回调参数为异步函数编写单元测试,unit-testing,testing,kotlin,ktor,kotlin-multiplatform,Unit Testing,Testing,Kotlin,Ktor,Kotlin Multiplatform,我正在为我的kotlin多平台库编写通用测试,该库使用ktor客户端库实现API业务逻辑 我有一个函数,它将回调作为参数,使用协同路由向API发出请求,然后执行回调 下面是我想测试的UserApi类中函数的简化版本 fun <T : Any> fetch( requestBuilder: HttpRequestBuilder, deserializer: DeserializationStrategy<T>, callback: (Either&l

我正在为我的kotlin多平台库编写通用测试,该库使用ktor客户端库实现API业务逻辑

我有一个函数,它将回调作为参数,使用协同路由向API发出请求,然后执行回调

下面是我想测试的UserApi类中函数的简化版本

fun <T : Any> fetch(
    requestBuilder: HttpRequestBuilder,
    deserializer: DeserializationStrategy<T>,
    callback: (Either<ErrorMessage, T>) -> Unit)
{
    GlobalScope.launch(dispatcherIO) {
        val result: Either<ErrorMessage, T> =
        try {
            val returnObject: T = Json.parse(
                deserializer, 
                HttpClient().post(requestBuilder)
            )
            Either.Right(returnObject)
        } catch (e: Exception) {
            Either.Left(ErrorMessage(e.message))
        }
        withContext(dispatcherMain) { callback(result) }
    }
}

为什么要使用回调?对于协同程序,您可以使用
suspend
函数的返回值。它们可以在
runBlocking
中进行测试。我希望从iOS Swift调用fetch函数,我认为使用回调更容易、更流畅,但这可能不是最好的解决方案。为什么要使用回调?对于协同程序,您可以使用
suspend
函数的返回值。它们可以在
runBlocking
中进行测试。我希望从iOS Swift调用fetch函数,我认为使用回调更容易、更流畅,但这可能不是最好的解决方案
@Test
fun requestOK() {
    runTest { //runTest returns a platform specific runBlocking
        val UserApi().fetch(request, User.serializer()) {
            it.fold(
                { failure -> fail("must return success" },
                { user -> assertEquals(expectedUser, user) }
            )
        }
    }    
}