为了测试重复工作,我需要等待整整15分钟(参考文献)来测试重复性,这实在是不太高效。开发人员有没有更好、更快的方法来更早地测试呢?
您可以在15分钟之前测试PeriodicWorkRequest。
为此,您需要在androidx.work.testing
中提供WorkManagerTestInitHelper
。
首先,在应用程序或模块的build.gradle文件中添加以下依赖项:
//Current stable release is 2.3.4
androidTestImplementation "androidx.work:work-testing:2.3.4
接下来,您需要使用TestDriver
提供的setPeriodDelayMet
方法,该方法可用于指示间隔已完成,并在MIN_PERIODIC_INTERVAL_MILLIS(15分钟)之前执行PeriodicWorkRequest。
样例代码:
@Test
public void testPeriodicWork(Context context) throws Exception {
// Setup input data
Data input = new Data.Builder().put(KEY_1, 1).put(KEY_2, 2).build();
// Create periodic work request
PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(MyWorker.class, 15, TimeUnit.MINUTES)
.setInputData(input)
.build();
// Enqueue periodic request
WorkManager.getInstance(context).enqueueUniquePeriodicWork(WORKER_TAG, ExistingPeriodicWorkPolicy.REPLACE, request);
// Initialize testDriver
TestDriver testDriver = WorkManagerTestInitHelper.getTestDriver();
// Tells the testing framework the period delay is met, this will execute your code in doWork() in MyWorker class
testDriver.setPeriodDelayMet(request.getId());
}
val work = OneTimeWorkRequest.Builder(TheWorker::class.java).build()
WorkManager.getInstance().enqueue(work)