如何对WorkManager Worker进行单元测试?
这里是示例工人:
System.InvalidCastException: Unable to cast object of type 'Microsoft.Z3.AlgebraicNum' to type 'Microsoft.Z3.BoolExpr'.
at Microsoft.Z3.Context.MkBoolConst(String name)
at <StartupCode$FSI_0013>.$FSI_0013.main@() in C:\Users\...\Program.fs:line 3
Stopped due to error
}
答案 0 :(得分:4)
在Work Manager alpha10版本中,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
}
添加了一个构造函数,因此更容易传递输入WorkerParameters
注意:我在Worker类中创建了工厂方法,因此更容易读取在Worker中传递和使用的输入数据。
这是样本单元测试:
Data