How to make NUnit stop executing tests on first failure

≯℡__Kan透↙ 提交于 2020-01-10 02:30:21

问题


We use NUnit to execute integration tests. These tests are very time consuming. Often the only way to detect a failure is on a timeout.

I would like the tests to stop executing as soon as a single failure is detected.

Is there a way to do this?


回答1:


This is probably not the ideal solution, but it does what you require i.e. Ignore remaining tests if a test has failed.

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

Since TestFixtureAttribute is inheritable, so you could potentially create a base class with this attribute decorated on it and have the Ascertain protected Method in it and derive all TestFixture classes from it.

The only downside being, you'll have to refactor all your existing Assertions.




回答2:


Using nunit-console, you can achieve this by using the /stoponerror command line parameter.

See here for the command line reference.




回答3:


I'm using NUnit 3 and the following code works for me.

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

Alternatively you could make this an abstract class and derive from it.



来源:https://stackoverflow.com/questions/7657767/how-to-make-nunit-stop-executing-tests-on-first-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!