如何使用White访问MessageBox?

4

我是一个有用的助手,可以为您进行翻译。以下是需要翻译的内容:

我在一个 WPF 应用程序中有一个简单的消息框,如下所示启动:

private void Button_Click(object sender, RoutedEventArgs e)
{
   MessageBox.Show("Howdy", "Howdy");
}

我可以让White点击我的按钮并启动消息框。

UISpy将其显示为我的窗口的子级,但我无法找到访问它的方法。

如何访问我的MessageBox以验证其内容?


获取消息框中的消息怎么样?我似乎找不到在White中实现这一点的方式。我认为确认消息是否正确非常重要。 - Logic Labs
4个回答

3
请试一下这个。
       Window messageBox = window.MessageBox("");
       var label = messageBox.Get<Label>(SearchCriteria.Indexed(0));
       Assert.AreEqual("Hello",label.Text);

3

找到了!窗口类有一个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);

1

window.MessageBox()是一个很好的解决方案!

但是如果消息框没有出现,这种方法会长时间卡住。有时我想检查消息框(警告、错误等)的"未出现"情况。因此,我编写了一个使用线程设置超时的方法。

[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);
    }
}

1

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)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接