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?
Whereas the TestFixtureSetUp is where the test fixture, the required initial state of the system before tests are run, is initialized. Follow this answer to receive notifications.
The [TestFixture] attribute at the beginning indicates that this class is a test fixture so that NUnit can identify it as a runnable test class. Similarly NUnit uses attributes to indicate various properties of classes/methods. Then you see two methods tagged [SetUp] and [TearDown].
This is the attribute that marks a class that contains tests and, optionally, setup or teardown methods. Most restrictions on a class that is used as a test fixture have now been eliminated.
A Fixture uses a graph of ISpecimenBuilder s to serve requests to create auto-generated values (also known as Specimens or Anonymous Variables). Developers can use its parameterless constructor to obtain an instance based on the default configuration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With