我在推出如下一個WPF應用程序的簡單消息框:如何使用白色訪問MessageBox?
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
我能得到white點擊我的按鈕並啓動消息框。
UISpy顯示它作爲我窗口的孩子我無法制定出訪問它的方法。
如何訪問我的MessageBox以驗證其內容?
我在推出如下一個WPF應用程序的簡單消息框:如何使用白色訪問MessageBox?
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
我能得到white點擊我的按鈕並啓動消息框。
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);
如何在消息框中獲取消息?無論如何,我似乎無法在白色中找到這個。我認爲這個消息是正確的,這是非常重要的。
包含在白色源代碼中的是一些UI測試項目(測試白色本身)。
其中一項測試包括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();
}
}
顯然,用於顯示所述文本消息的標籤通過顯示在MessageBox窗口所擁有,並且其主要識別是在最大字值(65535)。
請試試這個
Window messageBox = window.MessageBox("");
var label = messageBox.Get<Label>(SearchCriteria.Indexed(0));
Assert.AreEqual("Hello",label.Text);
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);
}
}