In my application, I use WorkManager with Hilt for periodic requests that run once a day. this is necessary to clear data across in the Room DAO.
I need to do a mock for my PeriodicWorkRequest. For this, I use WorkManagerTestInitHelper for the test drive inside the androidTest directory.
Scheduler worker:
private fun schedulerWorker() {
val dailyWorkRequest =
PeriodicWorkRequest.Builder(ClearCacheWorker::class.java, 1, TimeUnit.DAYS)
.setInitialDelay(1, TimeUnit.DAYS)
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"CleanCacheWork",
ExistingPeriodicWorkPolicy.KEEP,
dailyWorkRequest
)
}
My work with Inject:
@HiltWorker
class ClearCacheWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val movieDao: MovieDao,
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
Log.d("WORK_MANAGER", "doWork is run")
return try {
movieDao.clearTable()
Log.d("WORK_MANAGER", "doWork is success")
Result.success()
} catch (e: Exception) {
Log.e("WORK_MANAGER", "${e.message}")
Result.retry()
} finally {
Log.d("WORK_MANAGER", "doWork completed")
}
}
}
My test (in androidTest):
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class WorkerTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
private lateinit var context: Context
@Before
fun setup() {
hiltRule.inject()
context = ApplicationProvider.getApplicationContext()
val config = Configuration.Builder()
.setMinimumLoggingLevel(android.util.Log.DEBUG)
.setExecutor(SynchronousExecutor())
.build()
WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
}
@Test
@Throws(Exception::class)
fun testPeriodicWork() {
val request = PeriodicWorkRequest.Builder(ClearCacheWorker::class.java, 1, TimeUnit.DAYS)
.build()
val workManager = WorkManager.getInstance(context)
val testDriver = WorkManagerTestInitHelper.getTestDriver()
workManager.enqueue(request).result.get()
testDriver?.setPeriodDelayMet(request.id)
val workInfo = workManager.getWorkInfoById(request.id).get()
assertThat(workInfo.state, `is`(WorkInfo.State.SUCCEEDED))
}
}
When I ran the WorkerTest, I got the next error:
java.lang.AssertionError:
Expected: is <SUCCEEDED>
but: was <FAILED>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
at com.example.jetmoviepoalim.worker.WorkerTest.testPeriodicWork(WorkerTest.kt:59)
Could not instantiate com.example.jetmoviepoalim.worker.ClearCacheWorker
java.lang.NoSuchMethodException: com.example.jetmoviepoalim.worker.ClearCacheWorker.
<init> [class android.content.Context, class androidx.work.WorkerParameters]
Help me understand and fix the error.