如何在C#中验证消息框弹出?

3
我正在编写一些测试,试图验证某个系统消息框是否弹出。就像 http://www.dotnetperls.com/messagebox-show 中所示。不过,MessageBox类是用来创建消息框的。那么我该如何捕获和验证系统生成的消息框,并对其进行操作呢?
例如:行动如下:
    1.click on some execute file.
    2.validate a warning messagebox pop up
    3.click on yes/no on the messagebox

有什么提示吗?

也许你可以使用AutoIt,看一下http://www.autoitscript.com/site/autoit/。 - yosbel
那会有点昂贵,但感谢您的建议。 - Qingshan Zhang
2个回答

1

我建议使用White自动化框架。

例如:

Window messageBox = WindowFactory.Desktop
                                 .DesktopWindows()
                                 .Find(w => w.Title.Contains("MessageBoxTitle"));
Button ok = messageBox.Get<Button>(SearchCriteria.ByText("OK"));
ok.Click();

-1

White Framework +1 !!

你可以查看我发布的关于断言消息框并使用messageBox.Get()方法点击确定按钮的答案。

参考:https://dev59.com/KEXRa4cB1Zd3GeqPq1U_#35219222

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

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