TestStack.White 为什么我可以找到一个带有 Application.GetWindows 的窗口,但不能找



编辑:在形成这个问题时,我没有注意到目标窗口是一个模态窗口,所以我尝试的方法都是错误的。 我应该使用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) {}

试试这个:

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

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

相关内容

最新更新