【问题标题】:How to fail test if UI element is not found?如果未找到 UI 元素,如何测试失败?
【发布时间】:2012-11-13 22:40:23
【问题描述】:

我使用一种搜索 UI 元素的方法:

public static bool findtopuielm(string uiitemname)
        {
            bool res = false;
            try
            {
                AutomationElement desktopelem = AutomationElement.RootElement;
                if (desktopelem != null)
                {
                    Condition condition = new PropertyCondition(AutomationElement.NameProperty, uiitemname);
                    AutomationElement appElement = desktopelem.FindFirst(TreeScope.Descendants, condition);
                    if (appElement != null)
                    {
                        res = true;
                    }

                }
                return res;
            }
            catch (Win32Exception)
            {
                // To do: error handling
                return false;
            }
        }

这个方法被另一个等待元素直到它出现在桌面上的方法调用。

public static void waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
        {
        for (int i = 1; i <= retries; i++)
        {
            if (findtopuielm(appname))

                break;
                Thread.Sleep(retrytimeout);

            }
        }

问题是当我调用最后一个函数时:

waittopuielm("测试");

即使找不到元素,它也总是返回 true,在这种情况下,我希望测试失败。 任何建议都会受到欢迎。

【问题讨论】:

    标签: c# ui-automation gui-testing


    【解决方案1】:

    您的 waittopuielem 方法似乎返回 void - 您的意思是要发布类似此版本的内容,它返回一个布尔值吗?

        public static bool waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
        {
            bool foundMatch = false;
            for (int i = 1; i <= retries; i++)
            {
                if (findtopuielm(appname))
                {
                    foundMatch = true;
                    break;
                }
                else
                {
                    Console.WriteLine("No match found, sleeping...");
                }
                Thread.Sleep(retrytimeout);
            }
            return foundMatch;
        }
    

    除此之外,您的代码似乎按我的预期工作。

    一个建议:在您的 findtopuielm 方法中,将桌面元素搜索中的 TreeScope 值从 TreeScope.Descendants 更改为 TreeScope.Children:

    AutomationElement appElement = desktopelem.FindFirst(TreeScope.Children, condition);
    

    TreeScope.Descendants 执行的递归搜索可能比您想要的要多 - 桌面元素的所有子元素以及这些元素的每个子元素(即按钮、编辑控件等)都将被搜索。

    因此,在搜索相对常见的字符串时找到错误元素的机会很高,除非您将 NameProperty PropertyCondition 与 AndCondition 中的其他属性结合起来以缩小搜索范围。

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多