How to unit test WorkManager Worker?
Here is sample Worker:
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
}
}
With Work Manager alpha10 release a constructor was added with WorkerParameters
so it is easier to pass input Data
Note: I created factory method in Worker class, so it is easier to read input data being passed and used in Worker.
Here is sample unit test:
@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)));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With