【问题标题】:how to unit test a function which called CoroutineScope.launch如何对名为 CoroutineScope.launch 的函数进行单元测试
【发布时间】:2020-05-22 07:55:54
【问题描述】:

鉴于suspend fun:

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

单元如何测试下面的fun2和fun3

第一季度: 调用suspend fun的函数:

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")
                }
    }
}

第二季度:

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")
                    }
        }
    }

【问题讨论】:

    标签: unit-testing kotlin kotlin-coroutines


    【解决方案1】:

    由于我们不想让测试中的顶级函数暂停,我们总是以阻塞方式运行它们。所以正确的方法是Q2。由于Q1 使用launch,所以它只是一劳永逸。 (我可能误解了你的问题,但我相信你在问这两种方法中哪一种更好。)

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 2014-02-08
      • 2019-04-15
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 2019-06-04
      相关资源
      最近更新 更多