如何比MIN_PERIODIC_INTERVAL_MILLIS更快地测试PeriodicWorkRequest?

时间:2018-08-27 12:37:58

标签: android android-workmanager

为了测试重复性工作,我需要等待整整15分钟(reference)来测试重复性,但这确实没有效率。开发人员有更好,更快的方法来更快地对此进行测试吗?

2 个答案:

答案 0 :(得分:0)

如果我很好地理解了您的问题,则需要测试Woker的工作,而不是定期的,那么您可以使用OneTimeWorkRequest

val work = OneTimeWorkRequest.Builder(TheWorker::class.java).build()
WorkManager.getInstance().enqueue(work)

答案 1 :(得分:0)

您可以比MIN_PERIODIC_INTERVAL_MILLIS早15分钟来测试PeriodicWorkRequest。

为此,您需要WorkManagerTestInitHelper中的androidx.work.testing

首先在您的应用或模块的build.gradle文件中添加以下依赖项:

//Current stable release is 2.3.4
androidTestImplementation "androidx.work:work-testing:2.3.4

接下来,您需要使用setPeriodDelayMet可用的TestDriver方法,该方法可以用来指示一个间隔已完成,并且比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());

}

您可以在https://developer.android.com/topic/libraries/architecture/workmanager/how-to/integration-testing#periodic-work

中找到有关测试PeriodicWorkRequest的更多信息。

https://developer.android.com/reference/androidx/work/testing/WorkManagerTestInitHelperhttps://developer.android.com/reference/androidx/work/testing/TestDriver上了解有关测试WorkManager的更多信息