【发布时间】:2012-11-23 03:40:43
【问题描述】:
有没有办法在 SWT-Widgets 上自动生成 ID,以便 UI-Tests 可以引用它们?我知道我可以使用 seData 手动设置 id,但我想以某种通用的方式为现有应用程序实现此功能。
【问题讨论】:
标签: java swt eclipse-rcp gui-testing ui-testing
有没有办法在 SWT-Widgets 上自动生成 ID,以便 UI-Tests 可以引用它们?我知道我可以使用 seData 手动设置 id,但我想以某种通用的方式为现有应用程序实现此功能。
【问题讨论】:
标签: java swt eclipse-rcp gui-testing ui-testing
您可以使用Display.getCurrent().getShells(); 和Widget.setData(); 为应用程序中的所有shell 递归分配ID。
设置 ID
Shell []shells = Display.getCurrent().getShells();
for(Shell obj : shells) {
setIds(obj);
}
您可以使用 Display.getCurrent().getShells(); 方法访问应用程序中所有活动的(未释放的)Shell。您可以遍历每个Shell 的所有子代,并使用Widget.setData(); 方法为每个Control 分配一个ID。
private Integer count = 0;
private void setIds(Composite c) {
Control[] children = c.getChildren();
for(int j = 0 ; j < children.length; j++) {
if(children[j] instanceof Composite) {
setIds((Composite) children[j]);
} else {
children[j].setData(count);
System.out.println(children[j].toString());
System.out.println(" '-> ID: " + children[j].getData());
++count;
}
}
}
如果Control 是Composite,它可能在复合材料中包含控件,这就是我在示例中使用递归解决方案的原因。
按 ID 查找控件
现在,如果您想在其中一个 shell 中找到 Control,我建议您采用类似的递归方法:
public Control findControlById(Integer id) {
Shell[] shells = Display.getCurrent().getShells();
for(Shell e : shells) {
Control foundControl = findControl(e, id);
if(foundControl != null) {
return foundControl;
}
}
return null;
}
private Control findControl(Composite c, Integer id) {
Control[] children = c.getChildren();
for(Control e : children) {
if(e instanceof Composite) {
Control found = findControl((Composite) e, id);
if(found != null) {
return found;
}
} else {
int value = id.intValue();
int objValue = ((Integer)e.getData()).intValue();
if(value == objValue)
return e;
}
}
return null;
}
使用 findControlById() 方法,您可以通过其 ID 轻松找到 Control。
Control foundControl = findControlById(12);
System.out.println(foundControl.toString());
链接
【讨论】: