简体   繁体   中英

Creating nested TestFixture classes with NUnit

I'm trying to partition a unit test class into logical groupings based on a specific scenario. However, I require to have a TestFixtureSetUp and TestFixtureTearDown that will run for the entire test. Basically I need to do something like this:

[TestFixture]
class Tests { 
    private Foo _foo; // some disposable resource

    [TestFixtureSetUp]
    public void Setup() { 
        _foo = new Foo("VALUE");
    }

    [TestFixture]
    public class Given_some_scenario { 
        [Test]
        public void foo_should_do_something_interesting() { 
          _foo.DoSomethingInteresting();
          Assert.IsTrue(_foo.DidSomethingInteresting); 
        }
    }

    [TestFixtureTearDown]
    public void Teardown() { 
        _foo.Close(); // free up
    }
}

In this case I get a NullReferenceException on _foo presumably because the TearDown is being called before the inner class is executed.

How can I achieve the desired effect (scoping of tests)? Is there an extension or something to NUnit I can use that would help? I'd rather stick with NUnit at this time and not use something like SpecFlow.

You can create an abstract base class for your tests, do all the Setup and Teardown work over there. Your scenarios then inherit from that base class.

[TestFixture]
public abstract class TestBase {
    protected Foo SystemUnderTest;

    [Setup]
    public void Setup() { 
        SystemUnterTest = new Foo("VALUE");
    }

    [TearDown]
    public void Teardown() { 
        SystemUnterTest.Close();
    }
}

public class Given_some_scenario : TestBase { 
    [Test]
    public void foo_should_do_something_interesting() { 
      SystemUnderTest.DoSomethingInteresting();
      Assert.IsTrue(SystemUnterTest.DidSomethingInteresting); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM