简体   繁体   English

如何对调用 CoroutineScope.launch 的 function 进行单元测试

[英]how to unit test a function which called CoroutineScope.launch

Given suspend fun :鉴于suspend fun

private suspend fun fun1(arugment1: String): NetworkResult<Unit>

how the unit test the following fun2 and fun3单元测试下面的fun2和fun3如何

Q1: the function which called suspend fun: Q1:调用暂停乐趣的function:

fun fun2(argument1: String) {
    launch {
        CustomService().fun1(argument1))
                .onSuccessEmpty { _: Int, _: Headers ->
                    Log.d("TEST", "onSuccessEmpty")
                }
                .onSuccess { _: Int, _: Headers, _: Unit ->
                    Log.d("TEST", "onSuccess")
                }.onError {
                    Log.d("TEST", "onError $it")
                }
    }
}

Q2:问题二:

fun fun2(argument1: String) {
        runBlocking {
            CustomService().fun1(argument1))
                    .onSuccessEmpty { _: Int, _: Headers ->
                        Log.d("TEST", "onSuccessEmpty")
                    }
                    .onSuccess { _: Int, _: Headers, _: Unit ->
                        Log.d("TEST", "onSuccess")
                    }.onError {
                        Log.d("TEST", "onError $it")
                    }
        }
    }

Since we never want to have top-level functions in our tests suspend, we always run them in a blocking manner.由于我们从不想让测试中的顶级函数挂起,所以我们总是以阻塞方式运行它们。 So the correct way would be Q2 .所以正确的方法是Q2 Since Q1 uses launch , it'd just fire-and-forget.由于Q1使用launch ,所以它只是一劳永逸。 (I might've misunderstood your question, but I believe you're asking which of the two ways is better.) (我可能误解了你的问题,但我相信你在问这两种方法中哪一种更好。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何测试是否调用了函数(单元测试角度) - how to test if function was called (unit test angular) 如何取消单元测试调用的功能 - how to cancel the function that unit test called times 如何对具有wcf客户端的服务进行单元测试 - How to do unit test a service which has wcf client called 如何对作为视子的函数进行单元测试 - How to unit test a function which as viewchild 如何对具有协程`GlobalScope.launch`的function进行单元测试 - How to unit test function that has coroutine `GlobalScope.launch` 如何测试在AngularJS单元测试中已调用此嵌套函数? - How do I test that this nested function was called in an AngularJS unit test? 如何对另一个函数调用的函数进行单元测试 - How can I unit test a function that is called by another function Mockito - 如果参数设置在另一个 function 调用的 function 中,如何进行单元测试 - Mockito - how to unit test if argument is set in a function called by another function 测试是否在Ruby on Rails单元测试中调用函数 - Test if a function is called in a Ruby on Rails unit test 如何对是否已调用函数进行单元测试? 依赖注入? - How to unit test if function has been called? Dependency injection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM