Search code examples
kotlintestingjunitmockito

Best way to test enqueueUniqueWork and cancelUniqueWork WorkManager


What is the best way to test the methods enqueueUniqueWork and cancelUniqueWork in Kotlin in Android? I only found answers for testing work with Id, but I have a unique name.


Solution

  • After a lot of searching, I found this tutorial: https://medium.com/@thefallen.class/unit-testing-workmanager-with-dependencies-8ffff7ef5476

    And also android documentation: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/integration-testing

    It is not possible to directly tests the methods enqueueUniqueWork and cancelUniqueWork with Mocks only.

    I needed libraries such as

    • androidx.test:core
    • androidx.work:work-testing
    • org.robolectric:robolectric

    androidx.work:work-testing allowed me to initialize a Test WorkerManager thanks to the context provided by androidx.test:core

    @RunWith(RobolectricTestRunner::class)
    class ClassTest{
       private lateinit classToTest: ClassToTest
       private lateinit context: Context
       
       @Before
       fun setUp(){
          context = ApplicationProvider.getApplicationContext()
          val config = Configuration.Builder()
                .setWorkerFactory((WorkerFactory.getDefaultWorkerFactory()))
                .setExecutor(SynchronousExecutor())
                .setMinimumLoggingLevel(Log.DEBUG)
                .build()
          WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
       }
    }
    

    Then, I managed to get the state of my unique enqueued work and cancelled work thanks to lines such as

    WorkManager.getInstance(context).getWorkInfosForUniqueWork("name").get()[0].state
    

    Which returned elements such as WorkInfo.State.CANCELLED or WorkInfo.State.ENQUEUED

    I am not 100% if this is the best method to do so, but it allowed me to test what I wanted. Hoping it could help anyone else