withContext(Dispatchers.IO) 不断在 DefaultDispatchers 上启动

问题描述

我正在使用 Robolectric 进行单元测试。我有一个 Worker,我想在 dispatchers.IO 上启动

为了使用我自己的调度程序,我在构造函数中将其作为参数传递。 为此,我使用工厂


class CacheWorkerFactory(private val coroutinedispatcher: Coroutinedispatcher = dispatchers.IO) :
    WorkerFactory() {

    override fun createWorker(
        appContext: Context,workerClassName: String,workerParameters: WorkerParameters
    ): ListenableWorker? {
        return when (workerClassName) {
            CacheWorker::class.java.name -> {
                CacheWorker(appContext,workerParameters,coroutinedispatcher)
            }
            else -> {
                null
            }
        }
    }
}

我在 CacheWorker 中的工作:

class CacheWorker(
    context: Context,workerParameters: WorkerParameters,private val coroutinedispatcher: Coroutinedispatcher = dispatchers.IO
) : CoroutineWorker(context,workerParameters) {

    override suspend fun doWork(): Result {
        val sessionHolder = SessionHolder(DataHolder(applicationContext))
        val authRequest = AuthRequests(sessionHolder,inputData)
        withContext(coroutinedispatcher) {
            authRequest.execute {
                println("Thread before launchCacheRequest is " + Thread.currentThread().toString())
                launchCacheRequest(sessionHolder,authRequest.getHerowAPI())
            }
        }

        return Result.success()
    } 

还有我的单元测试:

    @Before
    fun setUp() {
        context = ApplicationProvider.getApplicationContext()
        dataHolder = DataHolder(context)
        sessionHolder = SessionHolder(dataHolder)

        sessionHolder.saveOptinValue(true)
        db = HerowDatabase.getDatabase(context)
        zoneRepository = ZoneRepository(db.zoneDAO())
        poiRepository = PoiRepository(db.poiDAO())

        // Mandatory to test testLaunchUser
        sessionHolder.savedeviceid(UUID.randomUUID().toString())
        location = Mocklocation(context).buildLocation()

        val cacheWorkerFactory = CacheWorkerFactory(iodispatcher)

        worker = TestListenableWorkerBuilder<CacheWorker>(
            context,inputData = workDataOf(
                ** private data **
            )
        )
            .setWorkerFactory(cacheWorkerFactory)
            .build()
    }

当我启动此测试时:

    @Test
    fun testLaunchTokenCacheWorker() {
        runBlocking {
            println("Test: Thread is " + Thread.currentThread())
            val result = worker.doWork()
            assertthat(result,Is.`is`(ListenableWorker.Result.success()))
            Assert.assertTrue(sessionHolder.getAccesstoken().isNotEmpty())
        }
    }

我所有的 println() 显示

enter image description here

谁能告诉我为什么它没有按要求在 I/O 上启动?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)