当我使用:
WorkManagerTestInitHelper.initializeTestWorkManager(context);
WorkManager workManager = WorkManager.getInstance();
获取WorkManager实例,WorkManager未能实现重试。我将介绍最简单的测试:
public class WorkManagerTest {
Context context;
@Before
public void setUp() throws Exception {
context = InstrumentationRegistry.getTargetContext();
}
@Test
public void testWorker1(){
Constraints constraints = new Constraints.Builder()
.build();
OneTimeWorkRequest.Builder updateorderworkerBuilder =
new OneTimeWorkRequest.Builder(TestWorker1.class)
.setConstraints(constraints)
//MIN_BACKOFF_MILLIS == 10000
.setBackoffCriteria(BackoffPolicy.LINEAR,10000, TimeUnit.MILLISECONDS);
OneTimeWorkRequest workRequest = updateorderworkerBuilder.build();
WorkManager workManager = WorkManager.getInstance();
workManager.enqueue(workRequest);
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testWorker2(){
Constraints constraints = new Constraints.Builder()
.build();
OneTimeWorkRequest.Builder updateorderworkerBuilder =
new OneTimeWorkRequest.Builder(TestWorker2.class)
.setConstraints(constraints)
//MIN_BACKOFF_MILLIS == 10000
.setBackoffCriteria(BackoffPolicy.LINEAR,10000, TimeUnit.MILLISECONDS);
OneTimeWorkRequest workRequest = updateorderworkerBuilder.build();
WorkManagerTestInitHelper.initializeTestWorkManager(context);
WorkManager workManager = WorkManager.getInstance();
workManager.enqueue(workRequest);
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class TestWorker1 extends Worker {
/**
* Override this method to do your actual background processing.
*
* @return The result of the work, corresponding to a {@link Result} value. If a
* different value is returned, the result shall be defaulted to
* {@link Result#FAILURE}.
*/
@NonNull
@Override
public Result doWork() {
Log.d("TEST_WORKER", "inside doWork()1");
return Result.RETRY;
}
}
public static class TestWorker2 extends Worker {
/**
* Override this method to do your actual background processing.
*
* @return The result of the work, corresponding to a {@link Result} value. If a
* different value is returned, the result shall be defaulted to
* {@link Result#FAILURE}.
*/
@NonNull
@Override
public Result doWork() {
Log.d("TEST_WORKER", "inside doWork()2");
return Result.RETRY;
}
}
}
在 Logcat 中,我看到:
07-22 23:34:25.184 5346-5388/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:34:30.178 5346-5391/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:34:40.238 5346-5388/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:35:00.300 5346-5391/com.billst.app.debug D/TEST_WORKER: inside doWork()1
07-22 23:35:15.130 5346-5372/com.billst.app.debug D/TEST_WORKER: inside doWork()2
即使我独立执行 2 个测试,我也会得到相同的结果。我们看到 WorkManagerTestInitHelper 的使用 阻止了 WorkManager 完成工作的重试。
我是否正确使用WorkManagerTestInitHelper?