【问题标题】:TestStack.White Why can I find a window with Application.GetWindows but not with .GetWindow?TestStack.White 为什么我可以找到一个带有 Application.GetWindows 而不是 .GetWindow 的窗口?
【发布时间】:2018-01-03 02:32:20
【问题描述】:

编辑:在形成这个问题时,我没有注意到目标窗口是一个模态窗口,所以我尝试的方法是错误的。我应该一直使用 GetModal,而不是 GetWindow。将其留在这里作为未来旅行者的潜在参考

我正在尝试使用 TestStack.White 为我继承的大型 WPF 应用程序编写一些测试;我有一个创建子窗口的情况,我需要获取对它的引用。如果我遍历对 Application.GetWindows 的调用结果,我可以找到它,但我无法通过我能想象的 Application.GetWindow 的任何化身找到它。

这在以下示例中进行了说明(其中 name 是一个字符串)。该窗口在 foreach 循环中找到(只要我在迭代之前让线程休眠一秒钟,以便在单击其他内容后给窗口时间创建..)老实说,这个练习的全部目的只是为了得到摆脱这个 Thread.Sleep 代码气味,所以我想使用 GetWindow 及其内置的等待。

        Thread.Sleep(1000);

        foreach (Window window in app.GetWindows())
        {
            if (window.AutomationElement.Current.Name == name)
            {
                Assert.AreEqual(window.Title, name); // passes.. they match
                Assert.AreEqual(window.AutomationElement.Current.Name, name);  // passes.. they match
                var aIdCheck = window.AutomationElement.Current.AutomationId; // empty string
            }
        }

        try  // this fails.. (after 30s)
        {
            var testGetWindow = app.GetWindow(name);
        }
        catch (Exception ex)   {   }

        try // this fails too... (after 5s)
        {
            var testGetWindow = app.GetWindow(SearchCriteria.ByNativeProperty(AutomationElement.NameProperty, name), InitializeOption.NoCache);
        }
        catch (Exception ex) {}

        try // you guessed it.. fail..
        {
            var testGetWindow = app.GetWindow(SearchCriteria.ByText(name), InitializeOption.NoCache);
        }
        catch (Exception ex) {}

【问题讨论】:

    标签: c# wpf white-framework


    【解决方案1】:

    试试这个:

    var window = Retry.For(
                () => parent.GetWindows().First(x => x.Title.Contains(name)),
                TimeSpan.FromSeconds(5));
    

    如果它有效,我认为问题在于有多个进程/窗口以您正在寻找的名称运行。您的 foreach 循环有效,因为它不关心并且只是找到第一个,但是 GetWindow() 方法在这种情况下会中断。

    【讨论】:

    • 事实证明我的问题更多地与我所追求的是一个模态窗口这一事实有关,所以我应该使用 GetModal 而不是 GetWindow。这就是我与 White 一起学习所得到的 :) 将其标记为答案,因为如果我没有误解我的问题,这将是一个很好的使用方法。
    • @RookieRick 谢谢。这也是一个有趣的解决方案;我不会想到的。
    猜你喜欢
    • 1970-01-01
    • 2022-10-05
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多