NUnit Tutorial: A Complete Guide With Examples and Best Practices

  • Learning Hub
  • Selenium NUnit Tutorial: A Comprehensive Guide With Examples and Best Practices

OVERVIEW

NUnit is a popular open-source unit testing framework for C#. It is ported from the JUnit framework. It is used for the development and execution of tests with the .NET language. It also facilitates batch execution of tests through console runner (nunit-console.exe). The console runner helps in loading, exploring, and executing tests with the help of NUnit Test Engine.

What is NUnit Testing Framework?

NUnit is a unit testing framework for all .NET languages. This open source platform was initially ported from JUnit. However, the current version, NUnit 3.0, is completely rewritten and supports a wide range of .NET platforms.

Developers can write and execute automated tests for their code using the NUnit framework. NUnit is written in C# and can test code in any.NET language, including C#, VB.NET, and F#. The framework includes several assert methods for ensuring that the code under test is working properly. It also has a number of attributes that can be used to control test execution and set up and tear down the test environment. NUnit is a popular tool among developers to ensure that their code is high quality and free of defects.

In this tutorial, you will learn extensively about the NUnit testing framework, its environment setup, and how to run unit testing for your webpage with NUnit testing.

Environment Setup for NUnit Testing

Before starting to write the test script for NUnit testing, you have to establish an environment, download some libraries, and need to install some packages which will help you write and execute the NUnit test. Major testers and developers use VS codes for writing codes and scripts, so first download Visual Studio and follow these steps for setting up the environment:

  • Install necessary packages for the development of the Windows platform. And Sign In to the IDE to use features such as pushing codes to GitHub, Syncing settings and etc.
  • To perform automation tests on the NUnit framework, you need to install the NUnit framework and NUnit Test Adaptor. There are two different ways to install the NUnit Test Adaptor: using the Visual Studio extension or the NuGet package manager. However, it is more advantageous to download it from the Visual Studio extension(VSIX) because the extension will automatically update to the latest version.
  • Once your NUnit frameworks get ready, install Selenium WebDriver using NuGet Package Manager commands.

Deep dive into the blog on NUnit environmental setup to get step-by-step guidance about creating a setup for the NUnit framework for automation testing.

NUnit Test Automation with Selenium C#

NUnit framework is more recommended than other testing frameworks because of its suitability with Selenium. In NUnit testing, you can run test scripts from the console runner with a third-party automation testing tool or with the NUnit Test Adaptor inside Visual Studio. Follow these steps to install and run your first automation test in the Selenium C# framework.

  • Download the latest version of Visual Studio and select a required package for development on the Windows system.
  • After downloading Visual Studio install Selenium C# framework such as NUnit and NUnit Test Adaptor for Selenium automation.
  • Install Selenium WebDriver from NuGet Package Manager.

After building a setup for running the test, make sure that you download some Selenium webDriver files for the browsers on which you want to execute the test. Programming languages use particular interfaces to interact with browsers such an interface is called IwebDriver.

Here are some browsers and their download locations.

  • Opera: https://github.com/operasoftware/operachromiumdriver/releases
  • Firefox: https://github.com/mozilla/geckodriver/releases
  • Chrome: http://chromedriver.chromium.org/downloads

This setup is required for running tests in sequence on the NUnit framework. However, Selenium WebDriver is not enough to run tests parallelly. To run tests parallelly over different browsers, OS, and device combinations, Selenium Grid is a better option.

However, you need to download lots of browsers and OS for running tests parallelly on Selenium Grid which is not pocket friendly; for that, you will require a Cloud-based browser compatibility tools such as LambdaTest, where you can perform NUnit tests over 3000+ browsers and OS combinations.

We have a dedicated blog on how to run automation testing with the NUnit framework.

Selenium WebDriver Command for NUnit Test Automation

To interact with different web browsers, Selenium uses WebDriver commands. With the help of WebDriver commands, it automates certain browser actions such as opening, closing, maximizing windows, and many more.

Different languages, such as Python, C#, etc., have their own interface to interact with web browsers; the NUnit framework uses the IWebDriver interface for browser interaction.

Selenium WebDriver commands are browser commands to automate actions on browsers to perform tests. In NUnit testing, there are three different types of Selenium WebDriver commands.

Web Browser Commands: Those are used for managing different actions on browsers such as window open, close, minimize, etc.

Here are some important Web Browser Commands:

  • Url
  • Title
  • PageSource
  • Quit
  • Close
  • Navigate
  • Back()
  • Forward()
  • GoToUrl()
  • Refresh()

Web Element Commands: Those are used to manage different actions on web elements such as clicking on buttons, texting on Inbox, etc.

Here are some most useful Web Element Commands:

  • Click
  • Enabled
  • Displayed
  • Clear
  • Sendkeys
  • GetAttributes
  • GetCssValues
  • Submit
  • Text
  • TagName
  • Selected
  • Size

Drop Down Commands: These commands use for performing actions over drop-down elements on the window. Such as selecting deselecting on the drop-down menu.

Here are some most useful Drop Down Commands:

  • SelectByIndex
  • DeselectByIndex
  • SelectByText
  • DeselectByText
  • SelectByValue
  • DeselectByValue
  • DeselectAll
  • IsMultiple
  • Options
  • AllSelectedOptions

We have a dedicated blog on WebDrivers Commands for NUnit test automation for your better learning.

NUnit Parameterized Unit Test

NUnit testing framework supports parameterized unit tests since the NUnit 2.5 version, and it is extremely useful when it is used with Selenium WebDriver. You can use certain attributes in your NUnit test and can make reliable test scripts to validate them over different browsers, versions, and OS, which can be passed as test parameters.Here are attributes in NUnit framework for parameterized NUnit test:

  • TestCase Attribute: The TestCase attribute in NUnit testing is used to specify a single set of parameters in a parameterized method. A test marked as a TestCase attribute is considered a single test, and the set of arguments provided to the attribute specifies a different set of data that should be used during the test. It can appear one or more times in a test with a carrying value for the test case each time.
  • This attribute also supports many additional named parameters such as Author, Category, Description, ExpectedResult, TestName, etc.

  • TestCaseSource Attribute: Like TestCase Attribute, the TestCaseSource attribute can be used with any test method. In contrast to the TestCase attribute, which is intended to provide a straightforward compile-time constant as a parameter to the parameterized function, the TestCaseSource attribute can be used for complex parameter types.
  • Another major advantage of these attributes is that It is also possible to reuse the object or data that is a component of the function using the TestCaseSource attribute.

  • ValueSource Attribute: ValueSource attribute in NUnit testing is similar to the TestCase attribute except that it is used as a Method parameter. It doesn't seem convincing to use the ValueSource attribute to create parameterized tests for cross-browser testing because a list of tests is generated depending on the values provided by the ValueSource attribute.
  • TestFixutre Attribute: TestFixture Attribute in NUnit Testing is used to mark a class as a test fixture. The purpose of the TestFixture attribute is to provide a common set of setup and tear-down logic that run before and after each test method in a fixture. Argument values are supplied to the TestFixture NUnit attribute for an NUnit parameterized test.

In our blog about parameterized unit tests in NUnit testing, you can learn more about it.

Asserts in NUnit Test Automation

Assertions in NUnit testing are being used to check conditions that never occurred. For example, You can raise an assertion when the page title does not match the expected title.

Some more use cases of Assertions:

  • To check If the implementation is flawed, there may be a serious problem with the code.
  • Give the development team your thoughts on the source code.
  • To examine the code's potential preconditions and postconditions.

The NUnit testing framework has numerous asserts. Many testers use multiple assertions in a single test which is not good practice. Before NUnit 2.4 classic model gets used for NUnit asserts. NUnit 2.4 introduced constrain method that uses a single Assert Class method.

Here are five different categories of constraints in NUnit assert:

  • Equal Constraints
    • Equalto
    • NotEqualTo
  • Comparison Constraints
    • GreaterThan
    • GreaterThanOrEqualTo
    • LessThan
    • LessThanOrEqualTo
  • String Constraints
    • String Equal or Not Equal
    • String Equal with IgnoreCase
    • DoesContain
    • Empty
    • StartWith and EndWith
    • Regex(Does.Match)
  • Condition constraints
    • Empty
    • Null
    • Boolean
  • Collection Constraints
    • Greater Than
    • Less than
    • Not Null
    • Instance Of
    • Exactly X Items
    • Unique Items
    • Empty
    • Contains

We have a dedicated blog where you can learn in detail about all those constraints and How to use assert in the NUnit framework.

NUnit Annotation for Selenium Automation Testing

A tag that offers details about a class or method is called an annotation. Annotations instruct the underlying framework on how to read the code. In NUnit, annotations are inserted between [ ].

Annotations are used by the NUnit framework because they enable the construction of a more reliable framework. Additionally, because the implementation is covered by different annotations, the test code is now more understandable.

The main purpose of NUnit annotations is to provide guidance to the underlying framework for reading the source code. A DLL (Dynamic Link Library) is created once the code has been compiled and can be run through a GUI or on the console.

Here are some Annotations used in NUnit tests:

  • [SetUp]: Mark a method that must be executed before each test method. Per test class, there should be at least one method.
  • [TearDown]: It marks a method that should be called after each test method. There should be at least one method for this annotation.
  • [TestFixture]: It marks a class that contains tests.
  • [TestCase]: It marks a method with a parameter and also provides inline arguments.

In our blog dedicated to NUnit annotation, you can learn about annotations with examples.

Generate Test Reports in NUnit Test Automation

Whether it be manual or automated testing, test reports are a crucial component of all testing-related activities. Test results are used to track how automation testing efforts have changed over time. The same logic is true when automated browser testing is done with MSTest, xUNit, or NUnit.

In Selenium C#, Extend and Allure have preferred NUnit reporting tools. Both third-party tools must be installed from the NuGet gallery using the Package Manager Console instructions or the Visual Studio UI. Extend in most popular reporting tool so we will take deep dive to understand about it.

What is Extend Reports?

ExtentReport is a well-known multilingual test reporting tool that provides comprehensive details about the test status. You may produce interactive and thorough test reports using the Extent framework. ExtentReport is also available for the Java language in addition to the .NET framework.

he implementation of ExtentReports 4.NET Core is available here, and the Extent Framework source code is accessible on GitHub.

Advantages of Extend Reports:

  • Aids in the creation of incredibly customized HTML test reports that help in the visualization of the status of the tests run on the Selenium Grid.
  • ExtentReports are simple to set up and connect with Selenium Java frameworks like TestNG and JUnit as well as Selenium C# frameworks like NUnit, MSTest, and xUnit.
  • The methods OnNodeAdded, OnTestStarted, OnScreenCaptureAdded, etc., enable you to take actions (such as adding relevant logs) in response to a certain 'event' (such as a test starts, a screenshot being taken, a test being removed, etc.) in the tests.
  • The NUnit test report includes stepwise and pie-chart forms that give a high-level overview of how the tests performed (i.e., how many passed/failed) throughout execution

How to use Extend Reports for the Nunit testing framework?

The Extent framework uses an Observer design, in which the reporter (for example, ExtentHTMLReporter) attached to the framework acts as an "observer" and receives notifications of changes such as the creation of logs, etc. Some of the changes that were informed led to content updates in the report. Although the Extent framework has many features, we would only need a few classes for NUnit report production.

When using the Extent framework to create NUnit reports, the following are the main classes that are usually used:

  • ExtentHtmlReporter (for version 4.x) or ExtentV3HtmlReporter (for version 3.x)
  • ExtentReports
  • ExtentTest
  • MediaEntityBuilder

We have a devoted blog for generating test reports in the NUnit testing framework, where we have provided an A to Z description of report generation.

Parallel Execution in The NUnit Testing Framework

One of the primary objectives of any automation tester is to guarantee that the tests are done at the optimal rate. As tests can be performed concurrently against many "environments," Selenium's parallel execution is the place to start for accelerating test execution.

Parallel execution in NUnit testing is supported by SpecFlow. SpecFlow is the .NET-based framework for BDD (Behavior Driven Development) and acceptance-driven test development used by Selenium C# Automation testers.

There are a few options available in SpecFlow for Specflow Parallel Execution in Selenium. However, the amount of work required to parallelize with SpecFlow depends on how many external dependencies there are in the tests. Parallel test execution is only "possible" at the features (or class) level, not at the "scenario method" level, with Specflow NUnit.

Here are some important concepts you need to keep in mind while executing parallel tests in the NUnit framework:

  • Parallel test execution with AppDomain: In this test scenario, you will not require external dependencies, and the application solely relies on a static state (such as caches). Tests can be run parallel while being isolated by AppDomain.
  • Parallel test execution without AppDomain: Parallel test execution using this approach reduces the initialization footprint, lowering memory requirements. Here, Specflow Parallel Execution can be achieved without AppDomain isolation if the test scenarios do not rely on static fields.
  • Sharing data between Steps and Binding: When automating testing with SpecFlow and the NUnit framework, you will encounter scenarios in which data must be shared across different step definitions. It could be input data that is initialized in one step and then used in later steps of the feature file.

    ScenarioContext: It gets created for executing an individual scenario and gets disposed of once execution is finished.

    FeatureContext: It gets created for executing the first scenario from features and gets disposed of once the execution of the scenario for the feature is done.

  • Hooks in SpecFlow: Hooks (or event bindings) are sometimes used to perform additional automation logic, such as the setup required for running a test scenario. The [Binding] attribute should be added to the Class in order to use hooks.

    Because hooks are global, it is possible to define scope binding, filtered by tags, to limit their use to only certain circumstances or features. Unless expressly indicated, the execution order of Hooks for the same event is indeterminate.

Those were essential concepts regarding Parallel test execution with Selenium and NUnit testing framework. You can learn more with an example of Parallel execution with NUnit framework from our dedicated blog on it.

Frequently Asked Questions (FAQs)

What is NUnit testing in C#?

NUnit framework is a unit testing framework for .NET language programming such as C#. It is an open source program developed by the .NET foundation, which provides tools for writing and executing the unit test.

What is the test method in NUnit?

One way to designate a method inside a TestFixture class as a test is by using the Test property. If the first four letters are 'test', regardless of the case, a test method may also be found for backward compatibility with earlier versions of NUnit testing. You can enable this option by changing a variable in the test's configuration file.

What is NUnit in Selenium?

NUnit is a unit testing framework that is compatible with Visual Studio and Selenium WebDriver. The most popular unit testing framework for .NET applications is NUnit. A tester can debug the automated tests using NUnit, which also shows the test results in an understandable style.

Why is NUnit used?

For batch test execution, NUnit provides a console runner (nunit3-console.exe). The NUnit Test Engine, via which the console runner operates, allows it to load, browse, and run tests.

Was this article helpful?

Helpful

NotHelpful