NUnit - cleanup after test failure

后端 未结 11 967
盖世英雄少女心
盖世英雄少女心 2020-12-24 05:09

We have some NUnit tests that access the database. When one of them fails it can leave database in inconsistent state - which is not an issue, since we rebuild database for

11条回答
  •  清酒与你
    2020-12-24 06:03

    Another option is to have a special function that will throw your exceptions, that sets a switch in the testfixture that says an exception occured.

    public abstract class CleanOnErrorFixture
    {
         protected bool threwException = false;
    
         protected void ThrowException(Exception someException)
         {
             threwException = true;
             throw someException;
         }
    
         protected bool HasTestFailed()
         {
              if(threwException)
              {
                   threwException = false; //So that this is reset after each teardown
                   return true;
              }
              return false;
         }
    }
    

    Then using your example:

    [TestFixture]
    public class SomeFixture : CleanOnErrorFixture
    {
        [Test]
        public void MyFailTest()
        {
            ThrowException(new InvalidOperationException());
        }
    
        [Test]
        public void MySuccessTest()
        {
            Assert.That(true, Is.True);
        }
    
        [TearDown]
        public void CleanUpOnError()
        {
            if (HasLastTestFailed()) CleanUpDatabase();
        }
    }
    

    The only issue here is that the Stack trace will lead to the CleanOnErrorFixture

提交回复
热议问题