5

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.

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
Wayne Molina
  • 19,158
  • 26
  • 98
  • 163

1 Answers1

7

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); 
    }
}
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • 2
    But there's no way to nest another class under that `Given_some_scenario` class? The idea was to have the encompassing class be relative to the entire section (e.g. `CustomerTests`) and then have each subclass for the individual scenario (e.g. `When_searching_customers`) – Wayne Molina Jun 12 '12 at 19:54
  • Why not group through a hierarchical structure using inheritance? `When_searching_customers : CustomerTestBase`, `When_creating_a_customer : CustomerTestBase`, etc.? – Dennis Traub Jun 12 '12 at 19:58
  • That could actually work, now that I think about it! Thanks! – Wayne Molina Jun 12 '12 at 20:04
  • I think this question deserves a better answer; not that this isn't good in a wide range of cases, yet it would be nice with a definitive "yes" or "no". Nesting TestFixtures is a neat feature if your tests have multiple Datapoint Source's pr test, and you want some hierarchy to group the tests rather than an exploded flat list. – Casper Bang Feb 23 '22 at 09:31