xUnit和White测试失败清理

问题描述 投票:1回答:2

我开始研究使用XUnit进行白色UI测试。

我的测试的基本结构是

  • 打开应用程序
  • 测试一下
  • 关闭应用程序

当测试通过时,这非常有效。但是,当测试失败时,应用程序不会关闭。如果多个测试失败,则会导致我的应用程序打开很多实例。

为了解决这个问题,我使用try和finally块,但它不是很好。

是否有一个替代选项可以实现相同的清理行为,但看起来更好一点?像“RunOnAssertFail”方法一样?

[Fact]
public void MainWindowCreated()
{
    bool testFailed = false;

    Application application = Application.Launch(@"C:\Program\Program.exe");
    Window mainWindow = GetWindow(application, "MainWidndow", 500);

    try
    {
        testFailed = true;
        mainWindow.Should().NotBe(null, ". Main Widndow could not be found");
        testFailed = false;
    }
    finally
    {
        if (testFailed)
        {
            application.Close();
        }
    }

    /*
     * Rest of test case
     */

    application.Close();
}

private static Window GetWindow(Application application,
    string windowName,
    int timeoutAfterMilliseconds)
{
    Window window = null;

    try
    {
        window = Retry.For(
            () => application.GetWindows().First(
                windowX => windowX.Title.Trim().Equals(windowName.Trim())),
            TimeSpan.FromMilliseconds(timeoutAfterMilliseconds));
    }
    catch (InvalidOperationException)
    {

    }

    return window;
}

需要xUnitWhiteFluent Assertions来运行。

c# xunit white fluent-assertions
2个回答
0
投票

在玩完之后,我意识到断言是它抛出一个异常而不是实际断言。

因此,为了帮助整理它,try catch块更合适

try
{
    mainWindow.Should().NotBeNull("because this window is required for the rest of the test");
}
catch(XunitException)
{
    application.Close();
    throw;
}

但是,这仍然不理想。


0
投票

如何在测试类上实现IDisposable并使用它来清理?

© www.soinside.com 2019 - 2024. All rights reserved.