FindFirst始终返回null AutomationElement

时间:2012-05-29 21:09:04

标签: wpf nunit ui-automation automationelement

我正在尝试使用UI Automated框架测试一些自定义控件。我的一个控件有一个TextBox基类,另一个继承自Control。我可以通过我的测试找到我的第一个控件,但无论我使用TreeScope和属性条件的组合,我都无法在窗口中找到我的第二个自定义控件。

我在XAML中声明自定义控件,如下所示:

<Grid>
    <test:CustomTextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="customTextBox1" VerticalAlignment="Top" Width="120" />
    <test:CustomUserControl Height="25" HorizontalAlignment="Left" Margin="12,62,0,0" Name="customUserControl1" VerticalAlignment="Top" Width="119" />
</Grid>

我有一个类似下面的样本测试。

[Test]
public void TestUsingValuePattern()
{
    // Getting RootElement...
    AutomationElement rootElement = AutomationElement.RootElement;
    Assert.IsNotNull(rootElement);

    // Searching for Test Window...
    AutomationElement windowElement = rootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "TestWindow"));
    Assert.IsNotNull(windowElement);

    // Searching for Custom TextBox control...
    AutomationElement customElement1 = windowElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "customTextBox1"));
    Assert.IsNotNull(customElement1);

    // Searching for Custom User control
    AutomationElement customElement2 = windowElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "customUserControl1"));
    Assert.IsNotNull(customElement2);
}

第二个断言总是返回null,所以我甚至无法开始对它运行测试。这里有什么建议可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

看起来您可能需要设置AutomationId property in the XAML才能显示它 - 看起来Name属性看起来不像AutomationId。

您可能还希望使用inspect tool检查元素是否实际在自动化树中公开,并具有您期望的AutomationId或其他属性。

答案 1 :(得分:0)

请参阅下面的检查线程,您需要为每个控件使用AutomationId来获取使用它的元素。

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b0892b5c-3850-4518-8063-d4eb5a8d9781/