How to make NUnit stop executing tests on first fa

2019-02-12 06: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.