How to write Nunit Parameterized Test

On This Page What Is Parameterization in NUnit?

April 27, 2026 · 8 min read · Testing Guide

How to write Nunit Parameterized Test

NUnit, a popular C # examination model, supports parameterized tests to eliminate codification duplication and amend efficiency. Instead of writing freestanding test cases for different inputs, parameterization allow run a individual test with multiple information sets.

This is especially useful in cross-browser testing, where the same test runs across various browser configurations.

This guide explores NUnit parameterized tests, their benefits, and how to implement them effectively.

What Is Parameterization in NUnit?

NUnit is a wide used C # prove model known for its compatibility with, create it a preferred choice for.

Since variation 2.5, NUnit has supported parameterized tryout, allowing trial methods to have input value dynamically. This eliminate the motive for redundant test cases by enabling a single test to run with multiple data set.

NUnit ply assorted property to define test parameters, some permit inline argument spec, while others retrieve data from separate method or fields, ensuring flexibility and reusability in test performance.

Also Read:

Importance of Parameterization In NUnit

Below are the key reasons why Parameterization in NUnit is important:

  • Eliminates Code Duplication: A single test method can run with multiple inputs, reducing redundant trial cases.
  • Enhances : Ensures the application behaves aright with respective comment values.
  • Improves Maintainability: Changes in logic demand to be update only once, simplifying examination management.
  • Optimizes Test Execution: Running parameterized tests is fast than executing separate for each input.
  • Supports Cross-Browser Testing: Enables testing across different browsers and configurations expeditiously.

How to indite Nunit Parameterized Test

Parameterized tests in NUnit allow running the like test logic with different inputs, reducing redundancy and improving test efficiency.

Instead of writing multiple test methods for various input values, parameterized test facilitate execute a individual test method with multiple data sets. NUnit provides multiple techniques to pass parameters to test method, ensuring flexibility and simplicity of use.

Also Read:

Parameterization techniques in NUnit

There are Four ways to group the parameter and can be legislate to the test in Nunit

  1. Inline & # 8211; As Test Case Attribute
  2. Inline & # 8211; As Random Attribute, Range Attribute, Values Attribute
  3. Separate & # 8211; TestCaseSource Attribute
  4. Separate & # 8211; ValueSource Attribute

Read More:

Inline & # 8211; As Test Case Attribute

In this technique, Nunit uses the TestCase attribute to surpass the various data set at Test level. This proficiency is helpful when we require to recur consummate test for several information set. For the model we & # 8217; ll be utiliseBrowserStack ’ s demo coating

Attribute syntax is

[TestCase (“ input1 ”, “ input2 ”)]

For example,

using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; utilize System.IO; using System; using OpenQA.Selenium.Support.UI; namespace NunitSeleniumDemo {public class Tests {individual IWebDriver driver; [SetUp] public void Setup () {String route = Path.GetFullPath (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, `` .. \\ .. \\ .. \\ '')); driver = new ChromeDriver (path + `` \\drivers ''); driver.Manage () .Window.Maximize (); driver.Url = `` https: //bstackdemo.com/ '';} [TestCase (`` OnePlus '', `` 6 Product (s) ground. '')] [TestCase (`` Google '', `` 3 Product (s) found. '')] public void NunitSeleniumTest (String framework, String substance) {DefaultWait & lt; IWebDriver & gt; fluentWait = new DefaultWait & lt; IWebDriver & gt; (driver); fluentWait.Timeout = TimeSpan.FromSeconds (5); fluentWait.PollingInterval = TimeSpan.FromMilliseconds (250); fluentWait.Until (driver = & gt; driver.Title == `` StackDemo ''); driver.FindElement (By.XPath ($ '' // * [@ class='checkmark ' and contains (text (), ' {model} ')] '')) .Click (); driver.Manage () .Timeouts () .ImplicitWait = (TimeSpan.FromSeconds (6)); String searchResults = driver.FindElement (By.XPath (`` // * [@ class='products-found '] //span '')) .Text; Assert.AreEqual (searchResults, $ '' {message} ''); driver.FindElement (By.XPath ($ '' // * [@ class='checkmark ' and contains (text (), ' {model} ')] '')) .Click ();} [TearDown] public void tearDown () {driver.Close (); driver.Quit ();}}}

In this exemplar, reusing the like tryout for formalize the lookup result after clicking a specific phone model.

As observed, first declaring the Attribute with the value you need to pass at test point

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

[TestCase (`` OnePlus '', `` 6 Product (s) found. '')] [TestCase (`` Google '', `` 3 Product (s) institute. '')]

We incur these values as input parameter for our test method when Nunit lam, hence we declare two parameter for our test method

public void NunitSeleniumTest (String model, String message)

And now you can use these parameters in our code where the code clicks on the model and control the substance

driver.FindElement (By.XPath ($ '' // * [@ class='checkmark ' and contains (text (), ' {poser} ')] '')) .Click (); driver.Manage () .Timeouts () .ImplicitWait = (TimeSpan.FromSeconds (6)); String searchResults = driver.FindElement (By.XPath (`` // * [@ class='products-found '] //span '')) .Text; Assert.AreEqual (searchResults, $ '' {substance} ''); driver.FindElement (By.XPath ($ '' // * [@ class='checkmark ' and contains (text (), ' {model} ')] '')) .Click ();

In this way, you can reuse our exam for various datasets.

Inline Parameterization Using Random, Range, and Values Attributes

NUnit provides additional inline parameterization techniques—Random, Range, and Values attributes—to supply tryout methods with different sets of input data. These attributes decimate the need for hardcoding multiple test cases, get test scripts more concise and scalable

Range Attribute

In this proficiency, Nunit allows two array parameters, which can be passed to the examination method.

First parameter is the Values and the Second is the Range. Test repeats for all the Values cater for the range provided.

This can be used when you want to test various scope for a give Value.

In the below example, the value is a chooser, and the amount is the scope. With the yield selector, examination adds the Phone to the cart and validates the handcart with the quantity.

expend NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System.IO; expend System; use OpenQA.Selenium.Support.UI; namespace NunitSeleniumDemo {public class InlineDemo {private IWebDriver driver; [OneTimeSetUp] public void Setup () {String way = Path.GetFullPath (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, `` .. \\ .. \\ .. \\ '')); driver = new ChromeDriver (path + `` \\drivers ''); driver.Manage () .Window.Maximize (); driver.Url = `` https: //bstackdemo.com/ '';} [Test] public emptiness checkQuantity ([Values (`` .shelf-container '')] String selector, [Range (2,3,1)] int value) {DefaultWait & lt; IWebDriver & gt; fluentWait = new DefaultWait & lt; IWebDriver & gt; (driver); fluentWait.Timeout = TimeSpan.FromSeconds (5); fluentWait.PollingInterval = TimeSpan.FromMilliseconds (250); fluentWait.IgnoreExceptionTypes (typeof (FormatException)); fluentWait.Until (driver = & gt; driver.Title == `` StackDemo ''); driver.FindElement (By.CssSelector ($ '' {selector} .shelf-item: nth-of-type ({value}) .shelf-item__buy-btn '')) .Click (); driver.Manage () .Timeouts () .ImplicitWait = TimeSpan.FromSeconds (120); fluentWait.Until (driver = & gt; Int32.Parse (driver.FindElement (By.CssSelector (`` .float-cart__header .bag__quantity '')) .Text) == (value - 1)); int cartQty = Int32.Parse (driver.FindElement (By.CssSelector (`` .float-cart__header .bag__quantity '')) .Text); Assert.AreEqual (cartQty, (value-1));} [OneTimeTearDown] public void tearDown () {driver.Close (); driver.Quit ();}}}

Values Attribute

In this technique, Nunit allows two Values range parameters to be passed to the test. For every first value parameter, the Values in the Second parameter will be repeated.

Executing the below exemplar

[Test] public void inlineValueTest ([Values (1,2)] int value1, [Values (2, 3)] int value2) {Console.WriteLine (`` Value 1 is: `` + value2); Console.WriteLine (`` Value 2 is: `` + value2);}

The tests will be divided into

Random Attribute

In this proficiency, the Nunit allows you to pass Random Attribute Array with 1 to 3 parameters

Syntax:

Random (int count) Random (int minNumber, int MaxNumber, int reckoning)

In the below example, we are define the Random number to be in range from 0 to 10 and repeat the test for every value 3 times

Executing the below example

[Test] public nihility inlineValueTest ([Values (1,2)] int value1, [Random (0,10, 3)] int value2) {Console.WriteLine (`` Value 1 is: `` + value2); Console.WriteLine (`` Value 2 is: `` + value2);}

Nunit generates test with below combination

Separate & # 8211; TestCaseSource Attribute

In this technique, Nunit grant passing the data from different sources using Attribute[TestCaseSource]. This will allow us to keep the test data away from the test and can be expend to say the data from External sources like a JSON file or Database.

[TestCaseSource (nameof (UserData))] public void testReadingFromDataSource (String userName, String password) {Console.WriteLine (`` Value 1 is: `` + userName); Console.WriteLine (`` Value 2 is: `` + password);} stable object [] UserData = {new object [] {'' username1 '', '' passsword1 ''}, new object [] {'' username2 '', '' passsword2 ''}};

As we can see our tryout data is coming from a method calledUserDatawhich returns an array of objective. Nunit will run the test for every returning object array

Separate & # 8211; ValueSource Attribute

In this technique, Nunit allows us to pass named data germ at test method parameter level using attribute[ValueSource].

[Test] public void testReadingFromDataSource ([ValueSource (`` UserData '')] Object [] userObject) {Console.WriteLine (`` userName is: `` + userObject [0]); Console.WriteLine (`` password is: `` + userObject [1]);} static object [] UserData = {new object [] {'' username1 '', '' passsword1 ''}, new object [] {'' username2 '', '' passsword2 ''}};

As observed, theuserDataobjective now is employ to the exam method ’ s parameter. Nunit will render tests like below

Talk to an Expert

Integrating NUnit Selenium Tests with BrowserStack

Running NUnit parameterized tests on BrowserStack ’ s cloud infrastructure enable seamless cross-browser and cross-device establishment, secure robust test coverage.

  • : Test across existent mobile and desktop devices to sham.
  • Execution: Scale NUnit tests effortlessly by running them in parallel across multiple environs.
  • Zero Infrastructure Hassle: Eliminate the need for set up and conserve in-house test environments.
  • Detailed Debugging Tools: Capture screenshots, logarithm, and picture recordings to analyse tryout failure effectively.

Read More: on Integration between BrowserStack, NUnit & amp; Selenium.

Conclusion

Parameterization is a powerful way of implementing our tests in a flexible way and can be reused for various information sets if designed decent. This will reduce the repetitive tests and also allows us to Maintain the tests continue test data tidy. WithTestCaseSourcewe can easy proceed the tryout data outside the exam which will get the trial reusable against different test environments where examination data might vary.

Tags
84,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free