Search code examples
c#unit-testingnunit

When do I use the TestFixtureSetUp attribute instead of a default constructor?


The NUnit documentation doesn't tell me when to use a method with a TestFixtureSetup and when to do the setup in the constructor.

public class MyTest
{
    private MyClass myClass;

    public MyTest()
    {
        myClass = new MyClass();
    }

    [TestFixtureSetUp]
    public void Init()
    {
        myClass = new MyClass();
    }
}

Are there any good/bad practices about the TestFixtureSetup versus default constructor or isn't there any difference?


Solution

  • I think this has been one of the issues that hasn't been addressed by the nUnit team. However, there is the excellent xUnit project that saw this exact issue and decided that constructors were a good thing to use on test fixture initialization.

    For nunit, my best practice in this case has been to use the TestFixtureSetUp, TestFixtureTearDown, SetUp, and TearDown methods as described in the documentation.

    I think it also helps me when I don't think of an nUnit test fixture as a normal class, even though you are defining it with that construct. I think of them as fixtures, and that gets me over the mental hurdle and allows me to overlook this issue.