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 MyTe
There is difference between constructor and method marked with [TestFixtureSetUp]
attribute. According to NUnit documentation:
It is advisable that the constructor not have any side effects, since NUnit may construct the object multiple times in the course of a session.
So if you have any expensive initialization it is better to use TestFixtureSetUp
.
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 have often wondered what the need for [TestFixtureSetUp]
was, given that there is a simple, well understood first class language construct that does exactly the same thing.
My preference is to use constructors, to take advantage of the readonly keyword ensuring member variables cannot be reinitialised.
I think I have a negative good answer - the reason to use a constructor instead of the attribute is when you have an inheritence between test classes.
Only one method annotated with [TestFixtureSetup]
will be called (on the concrete class only), but the other fixture initializers will not. In this case I'd rather put the initialization in the constructor, which has a well-defined semantics for inheritance :)
An important difference between constructor and TestFixtureSetUp is that, in NUnit 2 at least, constructor code is actually executed on test enumeration, not just test running, so basically you want to limit ctor code to only populating readonly, i.e. parameter, values. Anything that causes side-effects or does any actual work needs to either be wrapped in a Lazy or done in the TestFixtureSetUp / OneTimeSetUp. So, you can think of the constructor as solely a place to configure the test. Whereas the TestFixtureSetUp is where the test fixture, the required initial state of the system before tests are run, is initialized.
The constructor and the SetUp
methods are used differently:
The constructor is run only once.
However, the SetUp
methods are run multiple times, before every test case is executed.