Summarize: StandardTestDispatcher vs UnconfinedTestDispatcher (in case of local unit test and instrumented test)
Reference:
official website TestDispatcher: https://developer.android.com/kotlin/coroutines/test#injecting-test-dispatchers
official website Instrumented Test: https://github.com/android/testing-samples/tree/master/unit/BasicUnitAndroidTest
example of Instrumented Test:https://github.com/android/testing-samples/tree/master/unit/BasicUnitAndroidTest
学习前思考:
StandardTestDispatcher() 和 UnconfinedTestDispatcher() 分别是什么?
Dispatcher和Scheduler有啥区别?
TestDispatcher() 与调度器的关系。
调度器与线程的关系。
test中,协程在队列中排队是排在哪?排在调度器中,还是线程上?
几次写下来的Test,为什么看起来大差不差,却有时候报错(得不到返回数据),有时候不报?
这些报错要如何修正呢?
写测试的时候经常遇见值没有返回的bug,上次看了官方的视频,将原因归结到了线程切换的问题上,写了一篇有关coroutine测试的总结。
当时是通过设置主调度程序解决了问题。解决了ViewModel还没有给Livedata赋值test就终止了的问题。
但是最近重新整理代码,大修了Test的时候,我发现把这个设置主调度程序的rule删除测试也能正常运行。
关键区别在于,后来写的测试为了使用resource中的文件来读取Json,添加了@RunWith(AndroidJUnit4::class)。
在本地单元测试中,封装 Android 界面线程的 Main 调度程序将无法使用,因为这些测试是在本地 JVM 而不是 Android 设备上执行的。如果被测试代码引用主线程,它会在单元测试期间抛出异常。
然而在后来写的代码中我加入了这个注释,使得一开始默认的Test worker线程被替换为了SDK 29 Main Thr