Run massively scalable performance tests on web, mobile, and APIs

Request a Demo
Jul. 5th, 2018

Top NUnit Annotations for You to Use

If you have a new project that uses .NET programming languages and you want to add unit tests, you can use open source NUnit.  NUnit is a test Framework like JUnit, where you can define your tests cases, tests suites and assertions. NUnit can run all the tests and show you a report. NUnit, like JUnit, enables test-driven development. You can also run your NUnit tests in Taurus.

 

Why should I use the NUnit framework?

 

  1. NUnit runs very well with .NET programming languages.
  2. It is open source and it is free.
  3. It is easy to integrate it with testing projects.
  4. NUnit works with many integrated runners including Resharper and TestDriven .NET.
  5. NUnit has frequent version updates.
  6. NUnit has a graphical user interface.
  7. Very easy integration with Visual Studio and other IDEs.

 

Learning to Use NUnit

 

Now let’s learn how to use NUnit.

 

learn to use nunit

 

First, download the NUnit Framework.  You can use various installation approaches.

  1. NUnit install via NuGet (If you are using Visual Studio). This is the preferred way. Use the other ways if you don’t have an internet connection
  2. Zip file download from here
  3. Combined Approach

 

After downloading, it’s now time to write your tests. You can write them on your local machine or in the cloud.

 

NUnit is basically composed of attributes, or annotations. These indicate to the framework to execute the tests that are implemented in the class, and also how to interpret them. Annotations tell the framework how to interpret the code. After this code is compiled, a dll file is generated that can be executed through a console or using the graphic interface. Tests also include assertions that allow checking and comparing values.

 

Important NUnit Annotations

 

Now let’s take a look at the annotations and how to use them. The annotations are very easy to use: just add the annotation between brackets before the method declaration. With the annotation you can define the test: behavior (specifying Setup or TearDown method), assertions for example performance assertions like MaxTime method, and information like the Category method.

 

AnnotationUsage
CategorySpecifies one or more categories for the test
CultureSpecifies cultures for which a test or fixture should be run
IndicatesIndicates that a test should be skipped unless explicitly run
IgnoreIndicates that a test shouldn't be run for some reason
MaxTimeSpecifies the maximum time in milliseconds for a test case to succeed
OneTimeSetUpIdentifies methods to be called once prior to any child tests
OneTimeTearDownIdentifies methods to be called once after all child tests
PlatformSpecifies platforms for which a test or fixture should be run
RandomSpecifies generation of random values as arguments to a parameterized test
RepeatSpecifies that the decorated method should be executed multiple times
RetryCauses a test to rerun if it fails, up to a maximum number of times
TearDownIndicates a method of a TestFixture called immediately after each test method
TestMarks a method of a TestFixture that represents a test
TestCaseMarks a method with parameters as a test and provides inline arguments
TimeoutProvides a timeout value in milliseconds for test cases
SetUpIndicates a method of a TestFixture called immediately before each test method

 

Let’s see some examples of the most common annotations

 

SetUp: We generally use this for code that needs to be executed before executing a test, with the purpose to not repeat the code in each test.

 

Example:

 

 [SetUp]
    public void Initialize() {
        
        //driver = new FirefoxDriver();
        browser = ConfigurationManager.AppSettings["browser"];
        
        switch (browser)
        {
            case "Chrome":
                driver = new ChromeDriver();
                break;
            case "Firefox":
                driver = new FirefoxDriver();
                break;
        }
        driver.Manage().Window.Maximize();
    }

 

In this case, every test inherited in the [SetUp] annotation with the Initialize() method will be used to decide which browser to use, to open the test and to maximize the window.

 

TearDown: This is an annotation that acts the opposite of [SetUp]. It means the code written with this attribute is executed last (after passing other lines of code).

 

Example:

 

  [TearDown]
    public void EndTest()
    {
        if (TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Failed) {
            test.Log(LogStatus.Fail, TestContext.CurrentContext.Result.Message);
        }
        if (TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed)
        {
            test.Log(LogStatus.Pass, "Test Succesfull. ");
        }

        driver.Close();
        report.EndTest(test);
        report.Flush();
        report.Close();
    }

 

Here we use [TearDown] annotation to close the browser and create a report of the runned tests. This report can be viewed in a log or in GUI modem and can also be integrated into CI (see further down).

 

Test: The declaration of the steps that are going to be executed in the test.

 

Example:

 

 [Test]
        public void testLogin(string user, string message)
        {
            HomePage objHomePage = new HomePage(driver);
            objHomePage.goToLogin();

            LoginPage objLoginPage = new LoginPage(driver);
            objLoginPage.loginWithUser(user);

            MyAccountPage objAccountPage = new MyAccountPage(driver);
            objAccountPage.waitForLoad();

            Assert.AreEqual(objAccountPage.UserMessage(),message);
        }

 

This is a simple login method that goes to the login page, sets the user and password in the respective fields, click on the login button and waits for the page to load. After that, it checks if the loaded page is correct with an assertion .

 

NUnit also provides us with several annotations to parametrize our tests. This functionality can be used with the annotations [TestCase ] and [TestCaseSource]

 

TestCase: This annotation replaces the annotation Test we saw before, and allows creating a set of tests that execute the same code with different data inputs. 

 

Example:

 

 [TestCase(user1, Welcome user1)]
    [TestCase(user2, Invalid User)]
    [TestCase(user3,Not Registered User)]

    public void testLogin(string user, string pw){}

 

In this example we defined that the test testLogin runs 3 times, and in each execution the data input is specified in the annotation of our Test Case.

 

TestCaseSource: This annotation is similar to the previous one and it’s used when the list of records is too big. It takes a public static property that it provides in every entry record. This allow us to load our record from a .csv file or from a database.

 

[TestCaseSource("TestCases")]
    public void testLogin(string user, string pw){}

 

In this case the script testLogin takes as data input every record that is stored in the property TestCases.  TestCases method return the data type TestCaseData that can hold any type of data and expected results

 

Example:

 

public static List<TestCaseData> TestCases
{
    get
    {
        var testCases = new List<TestCaseData>();
 
        using (var fs = File.OpenRead(@"C:\users.csv"))
        using (var sr = new StreamReader(fs))
        {
            string line = string.Empty;
            while (line != null)
            {
                line = sr.ReadLine();
                if (line != null)
                {
                    string[] split = line.Split(new char[] { ',' },
                        StringSplitOptions.None);
 
                    string  user= split[0];
                    string  expectedMessage = split[1];
 
                    var testCase = new TestCaseData(user).Returns(expectedMessage );
                    testCases.Add(testCase);
                }
            }
        }
 
        return testCases;
    }
}

 

NUnit Test Results

 

NUnit provides a console mode, the nunit-console, which facilitates its use in the continuous integration process. In the console, the pass-fail results are provided immediately and no subjective human judgments or interpretations of test results are required.

 

learn nunit annotations

 

NUnit also has a graphical user interface, similar to the one used in JUnit, which it makes it easy to use for JUnit users. In the GUI you can see the execution of the tests, the test that is running and how many tests succeeded and failed. You can also see the result of each step and each assertion.

 

analyze nunit test results

 

Running NUnit in Taurus

 

After creating your NUnit tests, you can run them in Taurus. Taurus adds additional options to running your tests, like test failure criteria, and also enables connecting your tests to BlazeMeter with the command -cloud. Read more here.

 

Install Taurus and get started today!

Interested in writing for our Blog? Send us a pitch!