Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Global Initialization in NUnit 3.2?

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

like image 291
Striter Alfa Avatar asked Mar 22 '16 15:03

Striter Alfa


People also ask

What is TestFixture attribute used in NUnit?

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].

How do I configure NUnit?

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#.

Does Setup run before every test NUnit?

In unit testing frameworks, Setup is called before each and every unit test within your test suite.

What is NUnit setup attribute?

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.


1 Answers

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() { /* ... */ }
}
like image 62
stuartd Avatar answered Sep 29 '22 06:09

stuartd