[英]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.