【问题标题】:How to re-run a fail Nunit Test 2.6.2如何重新运行失败的 Nunit 测试 2.6.2
【发布时间】:2020-09-19 17:43:03
【问题描述】:

我正在尝试重新运行失败的 Nunit 测试,主要是因为硒的脆弱性。

    [TearDown]
    public virtual void TearDown()
    {
        var testName = TestContext.CurrentContext.Test.FullName.Replace("Server.Tests.", string.Empty);

        if (TestContext.CurrentContext.Result.Status == TestStatus.Passed)
            return;
        else if (_testFailure < 3) {
            _testFailure++;
            Console.WriteLine($"\n {testName} {TestContext.CurrentContext.Result.Status}... Retrying attempt {_testFailure}");
            DbReloader.LoadUnitTestData(DbFactory);
            TestExecutionContext.CurrentContext.CurrentTest.Run(new NullListener(), TestFilter.Empty);

        }
        BrowserDriver.GetScreenshot()
                     .SaveAsFile($"{testName}.fail.png", ImageFormat.Png);
    }

问题是在再次运行测试后,由于原始测试失败,它将继续拆除测试。如何使用重试的测试结果覆盖 TestContext.CurrentContext.Result?

【问题讨论】:

    标签: c# selenium unit-testing nunit nunit-2.6


    【解决方案1】:

    不幸的是,RetryAttribute 仅在 NUnit 3 中可用。从长远来看,它已经存在了很长一段时间,已经在 2015 年实施。有什么原因不能升级你现在的 NUnit 版本使用?

    如果环境迫使你继续使用这样一个旧版本 (2012) 的 NUnit,实现你自己的 RetryAttriute 并不难。该定义可以存在于您的测试程序集中并引用您正在使用的 NUnit 版本。

    您可以在现有 V2 RepeatAttribute 之后对此类属性进行建模,还可以从 NUnit 3 中的 RetryAttribute 中获取一些提示。但是,后者基于一组完全不同的接口,因此无法使用未经修改。

    没有简单的方法可以有效地从TearDown 方法重新运行测试,因为直到TearDown 方法完成后测试才结束。实际上修改 NUnit 2.6.2 本身会更容易。

    综上所述,按照从易到难的顺序,你可以选择

    1. 升级到 NUnit 3
    2. 添加自定义 RetryAttribute
    3. 修改 NUnit 2.6.2

    【讨论】: