How to test WorkManager in Android?

Testing WorkManager in Android involves creating unit tests and instrumented tests to ensure that your background tasks run as expected. Below is a guide on how to test WorkManager using a simple example.

// Example of testing WorkManager import androidx.work.WorkManager; import androidx.work.WorkManagerTestInitHelper; import androidx.work.testing.WorkManagerTestInitHelper; import androidx.work.testing.WorkManagerTestRule; import androidx.work.WorkManager; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.rule.ActivityTestRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class MyWorkerTest { @get:Rule public final WorkManagerTestRule workManagerTestRule = new WorkManagerTestRule(); @Test public void testMyWorker() { // Initialize WorkManager WorkManagerTestInitHelper.initializeTestWorkManager(appContext); // Enqueue the work OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MyWorker.class).build(); WorkManager.getInstance(appContext).enqueue(request); // Test that the work is in the correct state WorkManagerTestInitHelper.getInstance().getWorkInfoByIdLiveData(request.getId()) .observeForever(workInfo -> { assertNotNull(workInfo); assertTrue(workInfo.getState().isFinished()); }); } }

WorkManager Android WorkManager testing Unit testing Instrumented testing Background tasks