In WorkManager without Hilt, how do you give a worker constructor dependencies through a custom WorkerFactory, and how do you test that worker?
answer
- reflection needs two parameters
- createWorker may return null
- Configuration.Provider and the manifest
- TestListenableWorkerBuilder.setWorkerFactory
- TestDriver fakes constraints
basics
~10 sSubclass WorkerFactory, build your worker in createWorker (return null to fall back to the default), set it with Configuration.Builder.setWorkerFactory from an Application implementing Configuration.Provider, and remove WorkManagerInitializer from the manifest. Test with TestListenableWorkerBuilder.setWorkerFactory.
solid answer
~40 sBy default WorkManager creates a worker by reflection through its `(Context, WorkerParameters)` constructor, so a worker that also needs an `UploadApi` can't be built and its work fails. I write a `WorkerFactory` whose `createWorker()` returns a new `PhotoUploadWorker(appContext, params, api)` for that class name and `null` for others, which falls back to reflection. I register it in an `Application` that implements `Configuration.Provider` with `Configuration.Builder().setWorkerFactory(factory).build()`. I also remove the `androidx.work.WorkManagerInitializer` meta-data from App Startup's provider with `tools:node="remove"`; otherwise WorkManager initializes at launch with the default configuration and my provider is never asked. To test, I build the worker with `TestListenableWorkerBuilder<PhotoUploadWorker>(context).setWorkerFactory(factory).build()` and call `doWork()`. For integration tests I use `WorkManagerTestInitHelper` with a `SynchronousExecutor` and its `TestDriver`.
code
kotlin · 59 linesinterface UploadApi {
suspend fun upload(uri: String): Boolean
}
class FakeUploadApi(private val succeeds: Boolean) : UploadApi {
override suspend fun upload(uri: String) = succeeds
}
class AppWorkerFactory(private val api: UploadApi) : WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters,
): ListenableWorker? = when (workerClassName) {
PhotoUploadWorker::class.java.name -> PhotoUploadWorker(appContext, workerParameters, api)
else -> null // fall back to the default reflection-based creation
}
}
class PhotoUploadWorker(
appContext: Context,
params: WorkerParameters,
private val api: UploadApi,
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val uri = inputData.getString("photo_uri") ?: return Result.failure()
return if (api.upload(uri)) Result.success() else Result.retry()
}
}
class BackupApp : Application(), Configuration.Provider {
private val api: UploadApi = object : UploadApi {
override suspend fun upload(uri: String): Boolean = TODO("real HTTP upload")
}
override val workManagerConfiguration: Configuration
get() = Configuration.Builder()
.setWorkerFactory(AppWorkerFactory(api))
.build()
}
@RunWith(AndroidJUnit4::class)
class PhotoUploadWorkerTest {
private val context: Context = ApplicationProvider.getApplicationContext()
@Test
fun failedUploadAsksForRetry() {
val worker = TestListenableWorkerBuilder<PhotoUploadWorker>(
context,
inputData = workDataOf("photo_uri" to "content://photos/1"),
)
.setWorkerFactory(AppWorkerFactory(FakeUploadApi(succeeds = false)))
.build()
val result = runBlocking { worker.doWork() }
assertEquals(ListenableWorker.Result.retry(), result)
}
}go deeper
Recall that WorkManager creates workers itself and that a WorkerFactory is how you pass extra constructor arguments.
Explain the factory contract (new instance, null fallback) and the two registration steps: Configuration.Provider plus removing WorkManagerInitializer from the manifest.
Diagnose an ignored provider, a not-initialized exception and failures after a worker rename, and test workers through the same factory with TestListenableWorkerBuilder and TestDriver.
Decide whether the team hand-writes one composed factory or adopts a DI framework's worker integration, and set the rule that worker class names are stable public names.
## Why a worker needs a factory WorkManager persists a worker's **class name** with each request, not an instance, and creates the instance itself when the work becomes eligible. Its default path uses reflection to call a constructor taking exactly `(Context, WorkerParameters)`. A worker that also needs an API client or a repository has no such constructor, so creation fails, WorkManager logs "Could not create Worker" and the work ends `FAILED`. A **`WorkerFactory`** is the hook that lets the app construct workers itself. Dependency-injection frameworks build on the same hook; Hilt's `@HiltWorker` with `HiltWorkerFactory` is one, and it is covered with Hilt. The hand-written version below needs no framework. ## Writing the factory ```kotlin class AppWorkerFactory(private val api: UploadApi) : WorkerFactory() { override fun createWorker( appContext: Context, workerClassName: String, workerParameters: WorkerParameters, ): ListenableWorker? = when (workerClassName) { PhotoUploadWorker::class.java.name -> PhotoUploadWorker(appContext, workerParameters, api) else -> null } } ``` The contract has four rules: - **Return a new instance every time.** Returning an instance that has already run throws `IllegalStateException`, whose message says `createWorker()` must always return a new instance. - **Return `null` for classes you don't handle.** WorkManager then falls back to reflection, so workers without extra dependencies keep working. - **Match on the persisted name.** `workerClassName` is whatever was stored at enqueue time. Renaming or moving a worker class breaks work already enqueued under the old name, unless the factory maps the old name to the new class. - **Compose factories** with `DelegatingWorkerFactory.addFactory()` when several feature modules each contribute one; it asks each in turn. ## Registering it: `Configuration.Provider` and the initializer 1. Make the `Application` implement `Configuration.Provider` and override `workManagerConfiguration` to return `Configuration.Builder().setWorkerFactory(factory).build()`. (Older Kotlin samples override `getWorkManagerConfiguration()`; in current WorkManager the interface exposes a property.) 2. Remove the default initializer. Since 2.6 WorkManager initializes through App Startup, so you remove only the `androidx.work.WorkManagerInitializer` meta-data entry inside `androidx.startup.InitializationProvider`, or the whole provider if nothing else uses App Startup. 3. Always obtain WorkManager with `WorkManager.getInstance(context)`. On first use WorkManager sees that the `Application` implements `Configuration.Provider` and initializes itself with your configuration: this is **on-demand initialization**, which also takes WorkManager off the startup path. ```xml <provider android:name="androidx.startup.InitializationProvider" android:authorities="${applicationId}.androidx-startup" tools:node="merge"> <meta-data android:name="androidx.work.WorkManagerInitializer" android:value="androidx.startup" tools:node="remove" /> </provider> ``` ## What goes wrong | Symptom | Cause | |---|---| | The factory is never called and workers fail to be created | the default initializer still ran at startup with the default configuration, so the provider was ignored | | `IllegalStateException`: "WorkManager is not initialized properly" | the initializer was removed but the `Application` does not implement `Configuration.Provider` | | "WorkManager is already initialized" | the app calls `WorkManager.initialize()` manually without removing the initializer | | Old enqueued work fails after a refactor | a worker class was renamed and no factory maps the old name | WorkManager ships a lint check for an incorrect `Configuration.Provider` setup. The same `Configuration.Builder` also sets `setMinimumLoggingLevel`, `setExecutor` and `setWorkerCoroutineContext`. ## Testing the worker - **Unit-level:** the `work-testing` artifact's `TestListenableWorkerBuilder<PhotoUploadWorker>(context)` builds a worker without initializing WorkManager. Call `.setWorkerFactory(AppWorkerFactory(fakeApi))` so the worker gets a fake dependency, set `setInputData` or `setRunAttemptCount` as needed, then call `doWork()` inside `runBlocking` and assert on the `Result`. It is the recommended way to test a `CoroutineWorker`; `TestWorkerBuilder` is the variant for a plain `Worker` that lets you pass the `Executor`. - **Retry paths:** `setRunAttemptCount(3)` on the builder lets a test check retry-limit logic, such as a worker that returns `Result.failure()` after three attempts, without running it three times. The test WorkManager runs a `CoroutineWorker` on `Dispatchers.Default` rather than the dispatcher your worker would use, which is another reason the documentation recommends `TestListenableWorkerBuilder` for coroutine workers. - **Integration-level:** `WorkManagerTestInitHelper.initializeTestWorkManager(context, config)` installs a test WorkManager. Configure it with your factory and a `SynchronousExecutor`, so `enqueue(...).result.get()` runs the work on the spot. `WorkManagerTestInitHelper.getTestDriver()` returns a **`TestDriver`** with `setAllConstraintsMet(id)`, `setInitialDelayMet(id)`, `setPeriodDelayMet(id)` and, since 2.11, `stopRunningWorkWithReason(id, reason)`. With it you can check that a constrained, delayed or periodic request reaches the expected `WorkInfo.State` without waiting.
- You renamed UploadWorker to PhotoUploadWorker and old installs report failed uploads after the update; why?WorkManager stores the worker's fully qualified class name with each request. After the rename, work enqueued before the update still names the old class, so creating it fails and the work ends `FAILED`. Map the old name to the new class in your `WorkerFactory`, or keep a class under the old name, until the old work has drained.
- How do you test that a request with a network constraint and an initial delay eventually succeeds, without waiting?Initialize a test WorkManager with `WorkManagerTestInitHelper.initializeTestWorkManager(context, config)` using a `SynchronousExecutor`, enqueue the request, then call `getTestDriver()` and `setAllConstraintsMet(request.id)` and `setInitialDelayMet(request.id)`. Read `getWorkInfoById(request.id).get().state` and assert `SUCCEEDED`.
- WorkManager can inject any constructor parameter of a worker by reflection.
- Implementing Configuration.Provider is enough; the default initializer can stay in the manifest.
- A WorkerFactory may return the same worker instance for every run.
- createWorker() must handle every worker class or WorkManager throws.
- Testing a CoroutineWorker requires a fully initialized WorkManager and a real scheduler.
Assumes WorkManager 2.12; the default initializer runs through App Startup since 2.6.0, and TestDriver.stopRunningWorkWithReason exists since 2.11.0.