如何解决SWTBot操作弹窗时的WidgetNotFoundException问题?
SWTBot弹窗控件找不到(WidgetNotFoundException)的通用解决办法
问题场景
在使用SWTBot自动化操作时,多次遇到弹窗弹出后代码无法定位到控件,抛出WidgetNotFoundException的情况:
- 打开"Open Perspective"弹窗后,无法找到表格控件
- 点击"Create ontology set..."弹出窗口后,无法找到输入框控件
虽然已有透视图激活的临时解决方案,但弹窗处理的通用问题仍未解决。
通用解决办法
1. 显式等待控件加载
弹窗加载可能存在延迟,SWTBot默认等待时间不足以让控件完全渲染。可以通过waitUntil方法显式等待控件可见:
// 等待"Open Perspective"弹窗中的表格加载完成 bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.table().isVisible(); } }, 5000); // 设置5秒超时,可根据实际调整 SWTBotTable table = bot.table(); table.select("Manage Ontologies");
针对创建本体集的输入框,同样可以用等待逻辑:
workspace.contextMenu("Create ontology set...").click(); // 等待输入框可见 bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.textWithLabel("&Working set name:").isVisible(); } }, 5000); bot.textWithLabel("&Working set name:").setText("OntoSetContentFilters");
也可以用简化的链式调用:
bot.table().waitUntilVisible(5000);
2. 定位弹窗独立Shell
部分弹窗是独立的Shell窗口,直接用全局bot定位控件可能出现混淆。先定位到弹窗Shell再操作内部控件:
// 打开透视图弹窗后,定位对应Shell SWTBotShell perspectiveShell = bot.shell("Open Perspective"); perspectiveShell.activate(); // 激活弹窗窗口 SWTBotTable table = perspectiveShell.bot().table(); table.select("Manage Ontologies"); perspectiveShell.bot().button("Open").click();
创建本体集弹窗的处理方式:
workspace.contextMenu("Create ontology set...").click(); SWTBotShell createSetShell = bot.shell("Create ontology set"); createSetShell.activate(); createSetShell.bot().textWithLabel("&Working set name:").setText("OntoSetContentFilters"); createSetShell.bot().button("Finish").click();
3. 调整全局等待超时
如果频繁遇到控件加载慢的问题,可以全局设置SWTBot的超时时间:
bot.setTimeout(5000); // 将全局超时设为5秒
4. 验证控件标识准确性
确保代码中使用的控件label、title与实际UI完全匹配。如果存在加速键(如&Working set name:中的&)导致匹配失败,可尝试模糊查找:
// 遍历所有文本框,通过包含关键词匹配 List<SWTBotText> texts = bot.texts(); for (SWTBotText text : texts) { if (text.getLabel().contains("Working set name")) { text.setText("OntoSetContentFilters"); break; } }
内容的提问来源于stack exchange,提问作者Steve Vestal
相关产品推荐
相关产品推荐

