WorkManagerワーカーをユニットテストする方法は?
サンプルワーカーは次のとおりです。
public class SampleWorker extends Worker {
private static final String TAG = "SampleWorker";
private static final String WORKER_TAG = "SAMPLE";
static final String KEY_DATA_1 = "KEY_DATA_1";
static final String KEY_DATA_2 = "KEY_DATA_2";
public SampleWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
public static WorkRequest createWorkRequest(String data1, String data2) {
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
Data inputData = createData(data1, data2);
return new OneTimeWorkRequest.Builder(SampleWorker.class)
.setConstraints(constraints)
.setInputData(inputData)
.addTag(WORKER_TAG)
.build();
}
static Data createData(String data1, String data2) {
return new Data.Builder()
.putString(KEY_DATA_1, data1)
.putString(KEY_DATA_2, data2)
.build();
}
@NonNull
@Override
public Result doWork() {
try {
Data inputData = getInputData();
businessLogicHere(inputData.getString(KEY_DATA_1), inputData.getString(KEY_DATA_2));
return Result.SUCCESS;
} catch (Exception e) {
Log.e(TAG, "doWork failed", e);
return Result.FAILURE;
}
}
private void businessLogicHere(String data1, String data2) {
// no-op
}
}
Work Manager alpha10リリースでは、コンストラクターがWorkerParameters
で追加されたため、入力Data
を簡単に渡すことができます。
注:Workerクラスでファクトリメソッドを作成したので、Workerで渡されて使用される入力データを読みやすくなります。
サンプルの単体テストは次のとおりです。
@RunWith(PowerMockRunner.class)
@PrepareForTest({WorkerParameters.class})
public class SampleWorkerTest {
@Mock
Context context;
WorkerParameters workerParams;
Data inputData;
SampleWorker worker;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
workerParams = PowerMockito.mock(WorkerParameters.class);
inputData = SampleWorker.createData("data one", "data two");
when(workerParams.getInputData()).thenReturn(inputData);
worker = new SampleWorker(context, workerParams);
}
@Test
public void testCreateWorkRequestFactoryMethod() {
WorkRequest workRequest = SampleWorker.createWorkRequest("data one", "data two");
WorkSpec workSpec = workRequest.getWorkSpec();
// verify constraints
assertThat(workSpec.constraints.getRequiredNetworkType(), is(equalTo(NetworkType.CONNECTED)));
// verify input data
assertThat(workSpec.input.getString(SampleWorker.KEY_DATA_1), is(equalTo("data one")));
assertThat(workSpec.input.getString(SampleWorker.KEY_DATA_2), is(equalTo("data two")));
}
@Test
public void testDoWorkSuccess() {
Worker.Result result = worker.doWork();
// verify business logic here
assertThat(result, is(equalTo(Worker.Result.SUCCESS)));
}
}