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.
CodePudding user response:
Both methods came from WorkManager class. This class is an element of runtime environment, so testing of them is task of author of WorkManager.
What do you, probably, want to do is to test task executed/cancelled by those methods or test are they called.
For that second option please take a look at something called Mock. This is a special „class” that pretends your original class, but you can control how it behaves and check how it was used.
CodePudding user response:
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:coreandroidx.work:work-testingorg.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
