willem
willem

Reputation: 27027

How to make NUnit stop executing tests on first failure

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?

Upvotes: 20

Views: 13386

Answers (3)

Lukazoid
Lukazoid

Reputation: 19426

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

See here for the command line reference.

For nunit-console v3, it changes to --stoponerror (see here for the command line reference).

Upvotes: 29

Vapour in the Alley
Vapour in the Alley

Reputation: 496

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.

Upvotes: 27

Raghu
Raghu

Reputation: 2768

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.

Upvotes: -1

Related Questions