I've trying to design a test suit to run a global initialization before all my tests. We can consider that exists tests in differents classes and namespaces. In NUnit documentation I only found a attribute named OneTimeSetUp, but it works only for tests in the same namespace.
So, I designed using inherting. all my tests classes inhert a base test class where his constructor does the global inicialization (whith the help of a static variable to check if it was or not initialized), and the same to a global tear down in the destructor.
Using it I could create my scenario. But when the test suit runs, the base test class creates new objects because there are tests in differents classes and namespaces. It cause a overloard in the system and the next tests runs slow: the first test runs in 50 seconds, while another (that do the same thing but in a different namespace) runs in 120 seconds.
There is a better way to create a global inicialization and a global teardown without impact the test performance
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].
Navigate to Tools -> NuGet Package Manager -> Manager NuGet Packages for Solution. Search for NUnit & NUnit Test Adapter in the Browse tab. Click on Install and press OK to confirm the installation. With this installation, the NUnit framework can be used with C#.
In unit testing frameworks, Setup is called before each and every unit test within your test suite.
SetUpAttribute (NUnit 2.0 / 2.5) This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called. It is also used inside a SetUpFixture, where it provides the same functionality at the level of a namespace or assembly.
You are correct that OneTimeSetUp
only works for tests in the same namespace, but as the
SetUpFixture
documentation notes:
A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly.
So the class would look like this:
using System;
using NUnit.Framework;
[SetUpFixture]
public class TestInitializerInNoNamespace
{
[OneTimeSetUp]
public void Setup() { /* ... */ }
[OneTimeTearDown]
public void Teardown() { /* ... */ }
}
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