【发布时间】:2011-09-03 08:45:27
【问题描述】:
我今天正在学习 .NET UI 自动化框架。所以到目前为止我做了什么(参考各种文章)
有一个 WinForm,上面有 Listbox、PictureBox、TextBox 和 Button 控件。请参考图片:
我有一个控制台应用程序,其中包含所有 UI 自动化测试脚本或代码,可自动执行 winform UI 测试。
工作: 从列表框中选择项目后,图片框会加载一些图像并显示它(要加载的代码在列表框的 SelectedIndexChanged 事件中)。
下面是Forms listBox控件的代码:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.BackColor = Color.White;
pictureBox1.Image = imageCollection.ElementAtOrDefault(listBox1.SelectedIndex);
textBox1.Text = pictureBox1.Image.GetHashCode().ToString();
this.Refresh();
}
现在我的 UIAutomation 测试脚本代码如下:(仅显示必要部分)
AutomationElement listBoxElement = mainFormWindowElement.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "listBox1"));
Assert.IsNotNull(listBoxElement, "Cant find the listbox element");
AutomationElementCollection listBoxItems =
listBoxElement.FindAll(TreeScope.Children,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.ListItem));
AutomationElement itemToSelectInListBox = listBoxItems[new Random().Next(0, listBoxItems.Count - 1)];
Object selectPattern = null;
if (itemToSelectInListBox.TryGetCurrentPattern(SelectionItemPattern.Pattern, out selectPattern))
{
(selectPattern as SelectionItemPattern).AddToSelection();
(selectPattern as SelectionItemPattern).Select();
}
执行代码后,Select() 方法确实有效,Form 列表框项被选中,如图所示 :
如图所示,列表框项目已被选中,但 SelectedIndexChange 事件未触发,并且图片框未反映更改。
所以任何指针都会有很大帮助:)
谢谢
【问题讨论】:
-
我不知道是什么问题,但是您可以通过在声明
AutomationElement itemToSelectInListBox = listBoxItems[new Random().Next(0, listBoxItems.Count - 1)];之后添加listbox1_selectedIndexChanged(null,null);来临时解决问题 -
正如我所说,这个自动化 UI API 位于控制台应用程序(另一个项目和 exe)中,而表单位于另一个。正如你所说,我能做的唯一方法是使用 relfection api。但如果我这样做,那将是完全不同的实例,根本没有任何联系。
标签: c# winforms user-interface ui-automation microsoft-ui-automation