Creating Nested TestFixture Classes Using NUnit

I am trying to break the unit test class into logical groupings based on a specific scenario. However, I need to have TestFixtureSetUp and TestFixtureTearDown , which will be executed for the whole 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 TearDown is called before the inner class is executed.

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

+4
source share
1 answer

You can create an abstract base class for your tests, complete all Setup and Teardown tasks. Then your scripts are inherited from this 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); } } 
+6
source

All Articles