我在 WPF 应用程序中有一个简单的消息框,如下所示:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
我可以得到白色来单击我的按钮并启动消息框。
UISpy 将它显示为我的窗口的子窗口,我无法找出访问它的方法。
如何访问我的 MessageBox 以验证其内容?
我在 WPF 应用程序中有一个简单的消息框,如下所示:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
我可以得到白色来单击我的按钮并启动消息框。
UISpy 将它显示为我的窗口的子窗口,我无法找出访问它的方法。
如何访问我的 MessageBox 以验证其内容?
找到了!窗口类有一个 MessageBox 方法可以解决问题:
var app = Application.Launch(@"c:\ApplicationPath.exe");
var window = app.GetWindow("Window1");
var helloButton = window.Get<Button>("Hello");
Assert.IsNotNull(helloButton);
helloButton.Click();
var messageBox = window.MessageBox("Howdy");
Assert.IsNotNull(messageBox);
请试试这个
Window messageBox = window.MessageBox("");
var label = messageBox.Get<Label>(SearchCriteria.Indexed(0));
Assert.AreEqual("Hello",label.Text);
White 源代码中包含一些 UI 测试项目(用于测试 White 本身)。
其中一项测试包括 MessageBox 测试,其中包括获取显示消息的方法。
[TestFixture, WinFormCategory, WPFCategory]
public class MessageBoxTest : ControlsActionTest
{
[Test]
public void CloseMessageBoxTest()
{
window.Get<Button>("buttonLaunchesMessageBox").Click();
Window messageBox = window.MessageBox("Close Me");
var label = window.Get<Label>("65535");
Assert.AreEqual("Close Me", label.Text);
messageBox.Close();
}
[Test]
public void ClickButtonOnMessageBox()
{
window.Get<Button>("buttonLaunchesMessageBox").Click();
Window messageBox = window.MessageBox("Close Me");
messageBox.Get<Button>(SearchCriteria.ByText("OK")).Click();
}
}
显然,用于显示文本消息的标签归显示消息框的窗口所有,其主要标识是最大单词值(65535)。
window.MessageBox() 是一个很好的解决方案!
但是如果没有出现消息框,这个方法会卡很久。有时我想检查消息框(警告、错误等)的“未出现”。所以我写了一个方法来通过线程设置timeOut。
[TestMethod]
public void TestMethod()
{
// arrange
var app = Application.Launch(@"c:\ApplicationPath.exe");
var targetWindow = app.GetWindow("Window1");
Button button = targetWindow.Get<Button>("Button");
// act
button.Click();
var actual = GetMessageBox(targetWindow, "Application Error", 1000L);
// assert
Assert.IsNotNull(actual); // I want to see the messagebox appears.
// Assert.IsNull(actual); // I don't want to see the messagebox apears.
}
private void GetMessageBox(Window targetWindow, string title, long timeOutInMillisecond)
{
Window window = null ;
Thread t = new Thread(delegate()
{
window = targetWindow.MessageBox(title);
});
t.Start();
long l = CurrentTimeMillis();
while (CurrentTimeMillis() - l <= timeOutInMillsecond) { }
if (window == null)
t.Abort();
return window;
}
public static class DateTimeUtil
{
private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long currentTimeMillis()
{
return (long)((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);
}
}