Iva*_*nko 0 java string object
我正在写测试方法setTask(Task task).和Task对象有几个领域,如
public String vehicle;
Run Code Online (Sandbox Code Playgroud)
方法setTask应该在不同的测试用例中使用,所以我希望这个字段有一个选项来接受值:
null - 在这个特殊情况下,该方法不应做任何事情;some string value - 例如 "", "Hello, World!", "Iso Isetta", ...random - 指示(以及null表示"无变化")的值,应该为与该字段对应的下拉列表选择随机值.所以,我能做些什么,使String是SpecialString它可以接受的值null,random&some string value?(顺便说一句:我不想将它设置为字符串值"RANDOM",并且该值是否等于"RANDOM"-string)
更新:我不是说random喜欢random value from a set of values,我的意思是random还有null,这是setTask()处理random(选择下拉随机),而不是从一组值传递一个随机字符串.
伪代码:
Task task = new Task();
task.vehicle = random; // as well as null
setTask(task)
Run Code Online (Sandbox Code Playgroud)
在setTask(任务任务)中:
if (task.vehicle == null) {
//skip
} else if (task.vehicle == random) {
// get possible values from drop-down list
// select one of them
} else {
// select value from drop-down list which is equal to task.vehicle
}
Run Code Online (Sandbox Code Playgroud)
不要分配固定String但使用Supplier<String>可以String动态生成的a :
public Supplier<String> vehicleSupplier;
Run Code Online (Sandbox Code Playgroud)
这样,您可以根据需要分配生成器功能:
static Supplier<String> nullSupplier () { return () -> null; }
static Supplier<String> fixedValueSupplier (String value) { return () -> value; }
static Supplier<String> randomSupplier (String... values) {
int index = ThreadLocalRandom.current().nextInt(values.length) -1;
return index > 0 && index < values.length ? values[index] : null;
}
Run Code Online (Sandbox Code Playgroud)
在使用中,这看起来像:
task.setVehicleSupplier(nullSupplier()); // or
task.setVehicleSupplier(fixedValueSupplier("value")); // or
task.setVehicleSupplier(randomSupplier("", "Hello, World!", "Iso Isetta"));
Run Code Online (Sandbox Code Playgroud)
你可以得到字符串
String value = task.vehicleSupplier().get();
Run Code Online (Sandbox Code Playgroud)
或者在getter函数中隐藏实现
class Task {
// ...
private Supplier<String> vehicleSupplier;
public void setVehicleSupplier(Supplier<String> s) {
vehicleSupplier = s;
}
public String getVehicle() {
return vehicleSupplier != null ? vehicleSupplier.get() : null;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)