TLDR:我想知道如何扩展 fit.TypeAdaptor 以便我可以调用一个期望参数作为默认实现的方法 TypeAdaptor 通过反射调用绑定(绑定?)方法并假设它是一个无参数方法......
更长的版本 - 我正在使用 fit 为我的系统构建一个测试工具(一个返回自定义对象排序列表的服务)。为了验证系统,我想我会使用 fit.RowFixture 来断言列表项的属性。
由于 RowFixture 期望数据是公共属性或公共方法,所以我想在我的自定义对象上使用包装器(比如 InstanceWrapper)——我还尝试实现上一个线程中给出的关于在 RowFixture 中格式化数据的建议。
问题是我的自定义对象有大约 41 个属性,我想为测试人员提供选择他们想要在这个 RowFixture 中验证哪些属性的选项。另外,除非我向我的 InstanceWrapper 类动态添加字段/方法,否则 RowFixture 将如何调用我的任何一个 getter,因为两者都希望属性名称作为参数传递(代码复制如下)?我扩展了 RowFixture 以绑定我的方法,但我不确定如何扩展 TypeAdaptor 以便它使用 attr 名称进行调用。有什么建议吗?
public class InstanceWrapper {
private Instance instance;
private Map<String, Object> attrs;
public int index;
public InstanceWrapper() {
super();
}
public InstanceWrapper(Instance instance) {
this.instance = instance;
init(); // initialise map
}
private void init() {
attrs = new HashMap<String, Object>();
String attrName;
for (AttrDef attrDef : instance.getModelDef().getAttrDefs()) {
attrName = attrDef.getAttrName();
attrs.put(attrName, instance.getChildScalar(attrName));
}
}
public String getAttribute(String attr) {
return attrs.get(attr).toString();
}
public String description(String attribute) {
return instance.getChildScalar(attribute).toString();
}
}
public class MyDisplayRules extends fit.RowFixture {
@Override
public Object[] query() {
List<Instance> list = PHEFixture.hierarchyList;
return convertInstances(list);
}
private Object[] convertInstances(List<Instance> instances) {
Object[] objects = new Object[instances.size()];
InstanceWrapper wrapper;
int index = 0;
for (Instance instance : instances) {
wrapper = new InstanceWrapper(instance);
wrapper.index = index;
objects[index++] = wrapper;
}
return objects;
}
@Override
public Class getTargetClass() {
return InstanceWrapper.class;
}
@Override
public Object parse(String s, Class type) throws Exception {
return super.parse(s, type);
}
@Override
protected void bind(Parse heads) {
columnBindings = new TypeAdapter[heads.size()];
for (int i = 0; heads != null; i++, heads = heads.more) {
String name = heads.text();
String suffix = "()";
try {
if (name.equals("")) {
columnBindings[i] = null;
} else if (name.endsWith(suffix)) {
columnBindings[i] = bindMethod("description", name.substring(0, name.length()
- suffix.length()));
} else {
columnBindings[i] = bindField(name);
}
} catch (Exception e) {
exception(heads, e);
}
}
}
protected TypeAdapter bindMethod(String name, String attribute) throws Exception {
Class partypes[] = new Class[1];
partypes[0] = String.class;
return PHETypeAdaptor.on(this, getTargetClass().getMethod("getAttribute", partypes), attribute);
}
}