gpt4 book ai didi

android - 如何对 WorkManager Worker 进行单元测试

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:34 27 4
gpt4 key购买 nike

如何对 WorkManager Worker 进行单元测试?

这是示例 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
}
}

最佳答案

随着 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)));
}
}

关于android - 如何对 WorkManager Worker 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52897474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com