【问题标题】:How to make NUnit stop executing tests on first failure如何让 NUnit 在第一次失败时停止执行测试
【发布时间】:2011-10-05 07:02:04
【问题描述】:

我们使用 NUnit 来执行集成测试。这些测试非常耗时。通常,检测故障的唯一方法是超时。

我希望在检测到单个故障后立即停止执行测试。

有没有办法做到这一点?

【问题讨论】:

  • 我相信这是特定于测试运行程序的问题,那么您如何运行测试? NUnit-console,msbuild NUnit 任务,另一个跑步者?

标签: nunit integration-testing


【解决方案1】:

使用 nunit-console,您可以通过使用 /stoponerror 命令行参数来实现。

有关命令行参考,请参阅here

【讨论】:

  • 我相信这是一种更好的方法。你让 NUnit 来处理这个问题,而不是干预这个过程,并且用不必要的东西污染测试代码!
【解决方案2】:

我正在使用 NUnit 3,以下代码适用于我。

public class SomeTests {
    private bool stop;

    [SetUp]
    public void SetUp()
    {
        if (stop)
        {
            Assert.Inconclusive("Previous test failed");
        }
    }

    [TearDown]
    public void TearDown()
    {
        if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
        {
            stop = true;
        }
    }
}

或者,您可以将其设为抽象类并从中派生。

【讨论】:

    【解决方案3】:

    这可能不是理想的解决方案,但它可以满足您的要求,即如果测试失败,则忽略剩余的测试。

    [TestFixture]
        public class MyTests
        {
            [Test]
            public void Test1()
            {
                Ascertain(() => Assert.AreEqual(0, 1));
            }
    
            [Test]
            public void Test2()
            {
                Ascertain(() => Assert.AreEqual(1, 1));
            }
    
            private static void Ascertain( Action condition )
            {
                try
                {
                    condition.Invoke();
                }
    
                catch (AssertionException ex)
                {
                    Thread.CurrentThread.Abort();
                }
            }
        }
    

    由于 TestFixtureAttribute 是可继承的,因此您可能会创建一个带有此属性的基类,并在其中包含 Ascertain protected Method 并从中派生所有 TestFixture 类。

    唯一的缺点是,您必须重构所有现有的断言。

    【讨论】:

    • 这是朝着正确方向迈出的一步。它只适用于断言,而不是例外。但这是一个有趣的想法......我也许可以为异常做一些类似的事情。
    • @willem 如果您先成功,请您发布您的异常解决方法。我也会继续努力的。
    • 你能不能把整个测试方法体封装在 Ascertain 中,只捕获所有异常?
    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2021-03-19
    • 2015-11-09
    相关资源
    最近更新 更多