私が使用する場合:
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を正しく使用していますか?