Testing initial delay on CoroutineWorker with Dependencies

496 Views Asked by At

I know that WorkManager provides a work-testing artifact for test workers and we can use TestListenableWorkerBuilder to test CoroutineWorker (see this link for more information). I found an medium article by Ian Roberts showing how to test CoroutineWorker with dependencies by creating your own WorkerFactory.

According to official documentation, we can test initial delays on Worker using TestDriver but nothing was said about testing delays, constraints etc on CoroutinesWork. Is there a way to perform such tests in CoroutineWorker using TestListenableWorkerBuilder?

1

There are 1 best solutions below

0
Rômulo Silva On

After watching this video (at 13:00) from the 2019 Android Dev Summit, I found the answer for this question:

  1. When initializing workManager for test (by WorkManagerTestInitHelper.initializeTestWorkManager method), we have to pass our custom WorkerFactory through the configuration step;

  2. Setup your request worker as you normally would using the OneTimeWorkRequestBuilder method;

  3. By default, all constraints for Workmanager instances in the test mode are unmet. Using an instance of TestDriver, we can mark those constraints as met.

Here's an example to summarize these above steps:

@Test
fun checkInitialDelay() {
    val config = Configuration.Builder()
        .setWorkerFactory(
            MyWorkFactory(myDependencies)
        )
        .setMinimumLoggingLevel(Log.DEBUG)
        .setExecutor(SynchronousExecutor())
        .build()
    // Initialize WorkManager
    WorkManagerTestInitHelper.initializeTestWorkManager(context, config)

    //setup the request work
    val request =
        OneTimeWorkRequestBuilder<MyWork>()
            .setInitialDelay(10, TimeUnit.MINUTES)
            .build()

    val workManager = WorkManager.getInstance(context)
    // Get the TestDriver
    val testDriver = WorkManagerTestInitHelper.getTestDriver(context)
    // Enqueue
    workManager.enqueue(request).result.get()
    // Tells the WorkManager test framework that initial delays are now met.
    testDriver?.setInitialDelayMet(request.id)
    // Get WorkInfo and outputData
    val workInfo = workManager.getWorkInfoById(request.id).get()

    // Assert
    assert(workInfo.state == WorkInfo.State.SUCCEEDED)
}