Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-time initialization for NUnit

Tags:

c#

.net

nunit

Where should I place code that should only run once (and not once per class)?

An example for this would be a statement that initializes the database connection string. And I only need to run that once and I don't want to place a new method within each "TestFixture" class just to do that.

like image 575
code-ninja Avatar asked Jul 06 '10 16:07

code-ninja


People also ask

What is the use of OneTimeSetUp attribute?

This attribute is to identify methods that are called once prior to executing any of the tests in a fixture. It may appear on methods of a TestFixture or a SetUpFixture. OneTimeSetUp methods may be either static or instance methods and you may define more than one of them in a fixture.

What is TestFixture NUnit?

The [TestFixture] attribute denotes a class that contains unit tests. The [Test] attribute indicates a method is a test method. Save this file and execute dotnet test to build the tests and the class library and then run the tests. The NUnit test runner contains the program entry point to run your tests.

Does SetUp run before every test NUnit?

Inheritance. The SetUp attribute is inherited from any base class. Therefore, if a base class has defined a SetUp method, that method will be called before each test method in the derived class.


2 Answers

The [SetUpFixture] attribute allows you to run setup and/or teardown code once for all tests under the same namespace.

Here is the documentation on SetUpFixture. According to the documentation:

A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly.

So if you need SetUp and TearDown for all tests, then just make sure the SetUpFixture class is not in a namespace.

Alternatively, you could always define a static class strictly for the purpose of defining “global” test variables.

like image 62
Ben Hoffstein Avatar answered Sep 21 '22 09:09

Ben Hoffstein


Create a class (I call mine Config) and decorate it with the [SetUpFixture] attribute. The [SetUp] and [TearDown] methods in the class will run once.

[SetUpFixture] public class Config {     [SetUp]  // [OneTimeSetUp] for NUnit 3.0 and up; see http://bartwullems.blogspot.com/2015/12/upgrading-to-nunit-30-onetimesetup.html     public void SetUp()     {     }      [TearDown]  // [OneTimeTearDown] for NUnit 3.0 and up     public void TearDown()     {     } } 
like image 29
Jamie Ide Avatar answered Sep 20 '22 09:09

Jamie Ide