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

Why would you need to use a constructor in your test classes?

I use [SetUp] and [TearDown] marked methods for code to be executed before and after each test, and similarly [TestFixtureSetUp] and [TestFixtureTearDown] marked methods for code to be executed only once before and after all test in the fixture have been run.

I guess you could probably substitute the [TestFixtureSetUp] for a constructor (although I haven't tried), but this only seems to break from the clear convention that the marked methods provide.


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.


One thing you can't do with [TestFixtureSetup] that you can do in the constructor is receive parameters from the [TestFixture] .

If you want to parameterise your test fixture, then you will have to use the constructor for at least some of the set-up. So far, I've only used this for integration tests, e.g. for testing a data access layer with multiple data providers:

[TestFixture("System.Data.SqlClient",
  "Server=(local)\\SQLEXPRESS;Initial Catalog=MyTestDatabase;Integrated Security=True;Pooling=False"))]
[TestFixture("System.Data.SQLite", "Data Source=MyTestDatabase.s3db")])]
internal class MyDataAccessLayerIntegrationTests
{
    MyDataAccessLayerIntegrationTests(
        string dataProvider,
        string connectionString)
    {
        ...
    }
}