DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • Munit: Parameterized Test Suite
  • Error Handling Inside Kumologica Subflow
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  • Navigating Double and Triple Extortion Tactics
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. NUnit Tutorial: Parameterized Tests With Examples

NUnit Tutorial: Parameterized Tests With Examples

In this guide, we will showcase NUnit parameterized test cases along with the commonly used attributes like the TestFixture NUnit attribute.

By 
Himanshu Sheth user avatar
Himanshu Sheth
DZone Core CORE ·
May. 15, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.9K Views

Join the DZone community and get the full member experience.

Join For Free

Cross-browser testing has become an integral part of the test process to ensure the product experience and behavior remain consistent across different combinations of web browsers, devices, and operating systems. As testing has to be performed on varied combinations, it can lead to code duplication as a lot of test methods will be doing the same thing but on different input combinations. I have come across many such situations during the code optimization process when I felt that a part of the code is either duplicated or redundant.

One important lesson I learned from these situations is that you should never leave such activities for the future as it becomes more challenging to optimize with the increase in LOC (Lines of Code). This is where a parameterized test can be beneficial as it enables testing the code/methods against different input values. Test parameterization should be explored in cross-browser testing as the same tests need to be executed on different web browsers and different versions of the same web browser. In this blog, we learn how to execute NUnit parameterized tests with examples.

What Is Parameterization In NUnit?

NUnit is one of the widely used C# test frameworks for cross-browser testing as it is compatible with the Selenium test suite. NUnit supports parameterized tests since the release of NUnit 2.5. Test methods can have parameters, and various attributes are available that indicate what arguments should be supplied by the NUnit framework.

Some NUnit attributes enable specifying arguments inline, while other attributes use a separate method or field to hold the arguments.

We will use Visual Studio 2019 (Community Edition) for development, which can be downloaded from here.

Note: This blog will only focus on creating NUnit parameterized test examples that will aid you in the process of cross-browser testing or automated browser testing.

NUnit Parameterized Tests (Or Data-Driven Tests)

Parameterization of NUnit tests was introduced with version 2.5 (as mentioned above) and is considered extremely useful when used with the Selenium WebDriver. Using special attributes in NUnit, you can develop foolproof tests by verifying them on different browsers, browser versions, and platforms, which can be passed as parameters to the test.

To demonstrate an NUnit parameterized test example, we perform the test mentioned below:

  1. Open DuckDuckGo in the intended web browser.

  2. Locate the search box.

  3. Enter search query i.e., LambdaTest.

  4. Execute the search operation.

  5. Free up the resources.

You can refer to our detailed article on NUnit, which walks you through the implementation of executing the above-mentioned test without parameterization.

Cross-browser testing on the local Selenium grid can hit a roadblock as it is not feasible to have an in-house setup with different combinations of browsers, platforms, and devices.

Using a local Selenium grid for cross-browser testing can lead to a reduction of test coverage. Instead, cross-browser testing should be performed on cloud-based cross-browser testing platforms like LambdaTest, where testing can be performed on 2000+ browsers, thereby providing wider test coverage.

To get started, you should create an account on LambdaTest and note the user-name & access-key from the Profile Page. Desired capabilities can be generated using LambdaTest Capabilities Generator, and these capabilities enable to execute tests using different browser + OS combinations on remote Selenium grid. Along with parameterization, the prerequisite is that the tests have to be executed in parallel to complete test execution within a shorter time. With my current plan, I can execute five tests in parallel on the remote Selenium Grid on LambdaTest.

Let’s explore the different attributes in NUnit using which we can come up with an NUnit parameterized test:

TestCase Attribute

The TestCase attribute in NUnit marks a method with parameters as a test method. It also provides the inline data that needs to be used when that particular method is invoked. It can appear one or more times on the test method, with each appearance carrying values for the test case. Make more copies of the attribute if you want multiple cases. The data type of the values provided to the TestCase attribute should match with that of the arguments used in the actual test case.

This attribute that helps in coming up with an NUnit parameterized test also supports several additional named parameters like Author, Category, Description, ExpectedResult, TestName, etc. The execution order of the TestCase attribute can vary when used in combination with other data-providing attributes.

Demonstration – [TestCase] Attribute

The search for ‘LambdaTest’ on DuckDuckGo is carried out on the following browser + OS combinations.

BROWSER BROWSER VERSION PLATFORM/OPERATING SYSTEM
Chrome 72.0 Windows 10
Internet Explorer 11.0 Windows 10
Safari 11.0 macOS High Sierra
Microsoft Edge 18.0 Windows 10

The complete implementation is below:

C#
 




x
71


 
1
using System;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Remote;
4
using NUnit.Framework;
5
using System.Threading;
6
using System.Collections.Generic;
7
 
8
namespace ParallelLTSelenium
9
{
10
    [TestFixture]
11
    public class ParallelLTTests
12
    {
13
        ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();
14
        private String browser;
15
        private String version;
16
        private String os;
17
 
18
        [Test]
19
        [TestCase("chrome", "72.0", "Windows 10")]
20
        [TestCase("internet explorer", "11.0", "Windows 10")]
21
        [TestCase("Safari", "11.0", "macOS High Sierra")]
22
        [TestCase("MicrosoftEdge", "18.0", "Windows 10")]
23
        [Parallelizable(ParallelScope.All)]
24
        public void DuckDuckGo_TestCase_Demo(String browser, String version, String os)
25
        {
26
            String username = "user-name";
27
            String accesskey = "access-key";
28
            String gridURL = "@hub.lambdatest.com/wd/hub";
29
 
30
            DesiredCapabilities capabilities = new DesiredCapabilities();
31
 
32
            capabilities.SetCapability("user", username);
33
            capabilities.SetCapability("accessKey", accesskey);
34
            capabilities.SetCapability("browserName", browser);
35
            capabilities.SetCapability("version", version);
36
            capabilities.SetCapability("platform", os);
37
 
38
            driver.Value = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), capabilities, TimeSpan.FromSeconds(600));
39
 
40
            System.Threading.Thread.Sleep(2000);
41
 
42
            driver.Value.Url = "https://www.duckduckgo.com";
43
 
44
            IWebElement element = driver.Value.FindElement(By.XPath("//*[@id='search_form_input_homepage']"));
45
 
46
            element.SendKeys("LambdaTest");
47
 
48
            /* Submit the Search */
49
            element.Submit();
50
 
51
            /* Perform wait to check the output */
52
            System.Threading.Thread.Sleep(2000);
53
        }
54
 
55
        [TearDown]
56
        public void Cleanup()
57
        {
58
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
59
            try
60
            {
61
                // Logs the result to Lambdatest
62
                ((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
63
            }
64
            finally
65
            {
66
                // Terminates the remote webdriver session
67
                driver.Value.Quit();
68
            }
69
        }
70
    }
71
}


Code WalkThrough

Step 1 – The data of IWebDriver is stored per-thread basis, and that is the reason for using the ThreadLocal class.

public class ParallelLTTests {   ThreadLocal driver = new ThreadLocal();

Step 2 – The input combinations of browser, version, and platform constitute the parameters for the test case. These are supplied via the TestCase attribute. As the test has to be performed on four combinations, there are four occurrences of the attribute. The TestCase attribute is under the Test attribute, which defines the start of a test case.

As we want the test and its descendants to execute in parallel with other tests at the same level, ParallelScope is set to All using the Parallelizable attribute.

C#
 




xxxxxxxxxx
1


 
1
[Test]
2
[TestCase("chrome", "72.0", "Windows 10")]
3
[TestCase("internet explorer", "11.0", "Windows 10")]
4
[TestCase("Safari", "11.0", "macOS High Sierra")]
5
[TestCase("MicrosoftEdge", "18.0", "Windows 10")]
6
[Parallelizable(ParallelScope.All)]


Step 3 – We have not used the SetUp attribute as the steps being performed as a part of that attribute, i.e., creating instances of a remote Selenium WebDriver, setting browser capabilities, etc., are shifted to the TestCase attribute.

C#
 




xxxxxxxxxx
1
13


 
1
public void DuckDuckGo_TestCase_Demo(String browser, String version, String os)
2
{
3
    String username = "user-name";
4
    String accesskey = "access-key";
5
    String gridURL = "@hub.lambdatest.com/wd/hub";
6
 
7
    DesiredCapabilities capabilities = new DesiredCapabilities();
8
 
9
    capabilities.SetCapability("user", username);
10
    capabilities.SetCapability("accessKey", accesskey);
11
    capabilities.SetCapability("browserName", browser);
12
    capabilities.SetCapability("version", version);
13
    capabilities.SetCapability("platform", os);


Step 4 – The search box on DuckDuckGo is located using the XPath locator, for which we made use of the browser’s Inspect Tool. A search term is entered in the search box to perform the search operation. 

C#
 




xxxxxxxxxx
1


 
1
driver.Value.Url = "https://www.duckduckgo.com";
2
 
3
IWebElement element = driver.Value.FindElement(By.XPath("//*[@id='search_form_input_homepage']"));
4
 
5
element.SendKeys("LambdaTest");
6
 
7
/* Submit the Search */
8
element.Submit();


Step 5 – The resources used by the Selenium WebDriver instance is released as part of the TearDown attribute. 

C#
 




xxxxxxxxxx
1


 
1
[TearDown]
2
public void Cleanup()
3
{
4
      ...................
5
    ...................
6
    // Terminates the remote webdriver session
7
    driver.Value.Quit();
8
}


As seen in the execution snapshot, the data passed in the TestCase attribute is used as parameters for executing tests in DuckDuckGo_TestCase_Demo(String browser, String version, String os). 

As parallelism is enabled, the DuckDuckGo_TestCase_Demo test is executed on four different input combinations (supplied via the TestCase attribute) in one shot.

TestCaseSource Attribute

The TestCaseSource attribute can be applied to any test method, just like the TestCase attribute. The property, methods, or fields specified by the TestCaseSource attribute provide the arguments to the parameterized method. Unlike the TestCase attribute that is used to provide simple compile-time constants as parameters to the parameterized function, the TestCaseSource attribute can be used to provide more complicated parameter types.

The other major advantage of this attribute is that the source method is reusable across different tests. The object/data that is a part of the method using the TestCaseSource attribute can also be reused for multiple tests.

The source specified by the attribute can either return IEnumerable or a type that implements IEnumerable. For simple tests, object[] can be returned from the source. For more complicated tests, IEnumerable is used as the TestCaseData class provides additional test case information for a parameterized test, e.g., TestName, Result, ExpectedException, Properties, Result, etc.

For demonstrating the usage of TestCaseSource to create an NUnit parameterized test, the source method uses IEnumerable to provide values to the parameterized function.

Demonstration – [TestCaseSource] Attribute

We use the same test case that was used to showcase the usage of the TestCase attribute, i.e., a search for ‘LambdaTest’ is performed on the following browser and OS combinations.

BROWSER BROWSER VERSION PLATFORM/OPERATING SYSTEM
Chrome 72.0 Windows 10
Internet Explorer 11.0 Windows 10
Safari 11.0 macOS High Sierra
Microsoft Edge 18.0 Windows 10

The complete implementation is below:

C#
 




xxxxxxxxxx
1
75


 
1
using System;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Remote;
4
using NUnit.Framework;
5
using System.Threading;
6
using System.Collections.Generic;
7
 
8
namespace ParallelLTSelenium
9
{
10
    [TestFixture]
11
    [Parallelizable(ParallelScope.All)]
12
    public class ParallelLTTests
13
    {
14
        ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();
15
        private String browser;
16
        private String version;
17
        private String os;
18
 
19
        private static IEnumerable<TestCaseData> AddBrowserConfs()
20
        {
21
            yield return new TestCaseData("chrome", "72.0", "Windows 10");
22
            yield return new TestCaseData("internet explorer", "11.0", "Windows 10");
23
            yield return new TestCaseData("Safari", "11.0", "macOS High Sierra");
24
            yield return new TestCaseData("MicrosoftEdge", "18.0", "Windows 10");
25
        }
26
 
27
        [Test, TestCaseSource("AddBrowserConfs")]
28
        public void DuckDuckGo_TestCaseSource_Demo(String browser, String version, String os)
29
        {
30
            String username = "user-name";
31
            String accesskey = "access-key";
32
            String gridURL = "@hub.lambdatest.com/wd/hub";
33
 
34
            DesiredCapabilities capabilities = new DesiredCapabilities();
35
 
36
            capabilities.SetCapability("user", username);
37
            capabilities.SetCapability("accessKey", accesskey);
38
            capabilities.SetCapability("browserName", browser);
39
            capabilities.SetCapability("version", version);
40
            capabilities.SetCapability("platform", os);
41
 
42
            driver.Value = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), capabilities, TimeSpan.FromSeconds(600));
43
 
44
            System.Threading.Thread.Sleep(2000);
45
 
46
            driver.Value.Url = "https://www.duckduckgo.com";
47
 
48
            IWebElement element = driver.Value.FindElement(By.XPath("//*[@id='search_form_input_homepage']"));
49
 
50
            element.SendKeys("LambdaTest");
51
 
52
            /* Submit the Search */
53
            element.Submit();
54
 
55
            /* Perform wait to check the output */
56
            System.Threading.Thread.Sleep(2000);
57
        }
58
 
59
        [TearDown]
60
        public void Cleanup()
61
        {
62
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
63
            try
64
            {
65
                // Logs the result to Lambdatest
66
                ((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
67
            }
68
            finally
69
            {
70
                // Terminates the remote webdriver session
71
                driver.Value.Quit();
72
            }
73
        }
74
    }
75
}


The core implementation that involves the following remains the same as the [TestCase] attribute:

  1. Invocation of Selenium WebDriver in the target web browser.

  2. Generation of browser capabilities.

  3. Performing a search on DuckDuckGo, and

  4. Releasing the resources used by the WebDriver instance as a part of the TearDown attribute.

You can refer to steps 1, 3, 4, and 5 from the ‘Code WalkThrough’ section of [TestCase] attribute for more detailed information on how the above requirements are implemented in the code.

As shown in the snippet below, AddBrowserConfs() is the source method that returns IEnumerable. The browser capabilities are passed to the parameterized function, i.e., DuckDuckGo_TestCaseSource_Demo(String browser, String version, String os) through the TestCaseData attribute.

The test case information provided via TestCaseData matches the argument type being used in DuckDuckGo_TestCaseSource_Demo, i.e., the arguments should be of type String.

The TestCaseSource attribute uses the AddBrowserConfs method to supply parameters to the test case DuckDuckGo_TestCaseSource_Demo.

C#
 




xxxxxxxxxx
1
16


 
1
private static IEnumerable AddBrowserConfs()
2
{
3
     yield return new TestCaseData("chrome", "72.0", "Windows 10");
4
     yield return new TestCaseData("internet explorer", "11.0", "Windows 10");
5
     yield return new TestCaseData("Safari", "11.0", "macOS High Sierra");
6
     yield return new TestCaseData("MicrosoftEdge", "18.0", "Windows 10");       }
7
...................
8
...................
9
 
10
[Test, TestCaseSource("AddBrowserConfs")]
11
 
12
public void DuckDuckGo_TestCaseSource_Demo(String browser, String version, String os)
13
{
14
    ...................
15
    ...................
16
}


As shown in the execution snapshot, the four tests are executed in parallel on LambdaTest’s remote Selenium grid. The browser capabilities are passed to DuckDuckGo_TestCaseSource_Demo using the TestCaseSource attribute that is used on AddBrowserConfs, a parameterized test method.

ValueSource Attribute

The ValueSource attribute functions similarly like TestCaseSource, except that it is used as a Method parameter.

Using the ValueSource attribute for creating parameterized tests in NUnit for cross-browser testing does not sound convincing as a list of tests is prepared based on the values supplied via the ValueSource attribute. For example, the input values shown below generate four test cases, i.e., chrome 70.0, chrome 71.0, Firefox 70.0, and Firefox 71.0

C#
 




xxxxxxxxxx
1


 
1
private static string[] AddBrowserConfs = new string[] {
2
     "chrome",
3
     "Firefox"
4
};
5
 
6
private static string[] AddVerConfs = new string[] {
7
     "70.0",
8
     "71.0"
9
};


Demonstration – [ValueSource] Attribute

For demonstrating the usage of ValueSource attribute, a DuckDuckGo search for LambdaTest is performed on the following browser + OS combinations.

BROWSER BROWSER VERSION PLATFORM/OPERATING SYSTEM
Chrome 70.0, 71.0 Windows 10, macOS Mojave
Firefox 70.0, 71.0 Windows 10, macOS Mojave

The complete implementation is shown below:

C#
 




xxxxxxxxxx
1
84


 
1
using System;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Remote;
4
using NUnit.Framework;
5
using System.Threading;
6
using System.Collections.Generic;
7
 
8
namespace ParallelLTSelenium
9
{
10
    [TestFixture]
11
    [Parallelizable(ParallelScope.All)]
12
    public class ParallelLTTests
13
    {
14
        ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();
15
        private String browser;
16
        private String version;
17
        private String os;
18
 
19
        private static string[] AddBrowserConfs = new string[] {
20
            "chrome",
21
            "Firefox"
22
        };
23
 
24
        private static string[] AddVerConfs = new string[] {
25
            "70.0",
26
            "71.0"
27
        };
28
 
29
        private static string[] AddOsConfs = new string[] {
30
            "Windows 10",
31
            "macOS Mojave"
32
        };
33
 
34
        [Test]
35
        public void DuckDuckGo_ValueSource_Demo([ValueSourceAttribute("AddBrowserConfs")] String browser,
36
            [ValueSourceAttribute("AddVerConfs")] String version,
37
            [ValueSourceAttribute("AddOsConfs")] String os)
38
        {
39
            String username = "user-name";
40
            String accesskey = "access-key";
41
            String gridURL = "@hub.lambdatest.com/wd/hub";
42
 
43
            DesiredCapabilities capabilities = new DesiredCapabilities();
44
 
45
            capabilities.SetCapability("user", username);
46
            capabilities.SetCapability("accessKey", accesskey);
47
            capabilities.SetCapability("browserName", browser);
48
            capabilities.SetCapability("version", version);
49
            capabilities.SetCapability("platform", os);
50
 
51
            driver.Value = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), capabilities, TimeSpan.FromSeconds(600));
52
 
53
            System.Threading.Thread.Sleep(2000);
54
 
55
            driver.Value.Url = "https://www.duckduckgo.com";
56
 
57
            IWebElement element = driver.Value.FindElement(By.XPath("//*[@id='search_form_input_homepage']"));
58
 
59
            element.SendKeys("LambdaTest");
60
 
61
            /* Submit the Search */
62
            element.Submit();
63
 
64
            /* Perform wait to check the output */
65
            System.Threading.Thread.Sleep(2000);
66
        }
67
 
68
        [TearDown]
69
        public void Cleanup()
70
        {
71
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
72
            try
73
            {
74
                // Logs the result to Lambdatest
75
                ((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
76
            }
77
            finally
78
            {
79
                // Terminates the remote webdriver session
80
                driver.Value.Quit();
81
            }
82
        }
83
    }
84
}


Code WalkThrough

There are no changes in the core implementation for invoking the WebDriver instance, generating the browser capabilities, performing DuckDuckGo search, and performing de-initialization. You can refer to steps 1, 3, 4, and 5 from the ‘Code WalkThrough’ section of the TestCase attribute for more information.

Three string arrays consisting of browser type, browser versions, and platforms are created. These arrays are then passed as individual parameters to the test method (DuckDuckGo_ValueSource_Demo) using the ValueSource attribute.

A total of eight test combinations are generated from the input values passed to the test method i.e. (chrome + 70.0 + Windows 10), (chrome + 71.0 + macOS Mojave), (Firefox + 70.0 + Windows 10), (Firefox + 71.0 + macOS Mojave), etc.

C#
 




xxxxxxxxxx
1
23


 
1
private static string[] AddBrowserConfs = new string[] {
2
    "chrome",
3
    "Firefox"
4
};
5
 
6
private static string[] AddVerConfs = new string[] {
7
    "70.0",
8
    "71.0"
9
};
10
 
11
private static string[] AddOsConfs = new string[] {
12
    "Windows 10",
13
    "macOS Mojave"
14
};
15
 
16
[Test]
17
public void DuckDuckGo_ValueSource_Demo(
18
[ValueSource("AddBrowserConfs")]String browser, [ValueSource("AddVerConfs")] String version, [ValueSource("AddOsConfs")] String os
19
)
20
{
21
    ...................
22
    ...................
23
};


The execution snapshot below shows that eight test combinations are created from the test parameters supplied through the ValueSource attribute. 

TestFixture Attribute

The TestFixture NUnit attribute marks a class that contains tests. Parameterized and generic test fixtures were introduced in NUnit 2.5. For an NUnit parameterized test, argument values are passed to the TestFixture NUnit attribute. The NUnit framework constructs a separate instance of TestFixture for each set of arguments.

From NUnit 2.5, test fixtures can take constructor arguments. In the example shown below, the test fixture would be instantiated by the NUnit framework three times, passing each set of arguments to the appropriate constructor.

C#
 




xxxxxxxxxx
1


 
1
[TestFixture("chrome", "72.0", "Windows 10")]
2
[TestFixture("internet explorer", "11.0")]
3
[TestFixture("Safari", 11)]


Demonstration – [TestFixture] Attribute

A search for ‘LambdaTest’ is performed on the following browser and OS combinations.

BROWSER BROWSER VERSION PLATFORM/OPERATING SYSTEM
Chrome 72.0 Windows 10
Internet Explorer 11.0 Windows 10
Safari 11.0 macOS High Sierra
Microsoft Edge 18.0 Windows 10

The complete implementation is below:

C#
 




xxxxxxxxxx
1
83


 
1
using System;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Remote;
4
using NUnit.Framework;
5
using System.Threading;
6
using System.Collections.Generic;
7
 
8
namespace ParallelLTSelenium
9
{
10
    [TestFixture("chrome", "72.0", "Windows 10")]
11
    [TestFixture("internet explorer", "11.0", "Windows 10")]
12
    [TestFixture("Safari", "11.0", "macOS High Sierra")]
13
    [TestFixture("MicrosoftEdge", "18.0", "Windows 10")]
14
    [Parallelizable(ParallelScope.All)]
15
    public class ParallelLTTests
16
    {
17
        ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();
18
        private String browser;
19
        private String version;
20
        private String os;
21
 
22
        public ParallelLTTests(String browser, String version, String os)
23
        {
24
            this.browser = browser;
25
            this.version = version;
26
            this.os = os;
27
        }
28
 
29
        [SetUp]
30
        public void Init()
31
        {
32
            String username = "user-name";
33
            String accesskey = "access-key";
34
            String gridURL = "@hub.lambdatest.com/wd/hub";
35
 
36
            DesiredCapabilities capabilities = new DesiredCapabilities();
37
 
38
            capabilities.SetCapability("user", username);
39
            capabilities.SetCapability("accessKey", accesskey);
40
            capabilities.SetCapability("browserName", browser);
41
            capabilities.SetCapability("version", version);
42
            capabilities.SetCapability("platform", os);
43
 
44
            driver.Value = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), capabilities, TimeSpan.FromSeconds(600));
45
 
46
            System.Threading.Thread.Sleep(2000);
47
        }
48
 
49
        [Test]
50
        public void DuckDuckGo_TestFixtures_Demo()
51
        {
52
            {
53
                driver.Value.Url = "https://www.duckduckgo.com";
54
 
55
                IWebElement element = driver.Value.FindElement(By.XPath("//*[@id='search_form_input_homepage']"));
56
 
57
                element.SendKeys("LambdaTest");
58
 
59
                /* Submit the Search */
60
                element.Submit();
61
 
62
                /* Perform wait to check the output */
63
                System.Threading.Thread.Sleep(2000);
64
            }
65
        }
66
 
67
        [TearDown]
68
        public void Cleanup()
69
        {
70
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
71
            try
72
            {
73
                // Logs the result to Lambdatest
74
                ((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
75
            }
76
            finally
77
            {
78
                // Terminates the remote webdriver session
79
                driver.Value.Quit();
80
            }
81
        }
82
    }
83
}


Code WalkThrough

Step 1 – The browser and platform combinations are specified as arguments to the TestFixture attribute.

C#
 




xxxxxxxxxx
1


 
1
[TestFixture("chrome", "72.0", "Windows 10")]
2
[TestFixture("internet explorer", "11.0", "Windows 10")]
3
[TestFixture("Safari", "11.0", "macOS High Sierra")]
4
[TestFixture("MicrosoftEdge", "18.0", "Windows 10")]
5
[Parallelizable(ParallelScope.All)] 


Step 2 – The arguments supplied via the TestFixture NUnit attribute are passed to the constructor that has three parameters of type String. 

C#
 




xxxxxxxxxx
1


 
1
public ParallelLTTests(String browser, String version, String os)
2
{
3
    this.browser = browser;
4
    this.version = version;
5
    this.os = os;
6
}


Step 3 – The implementation related to the instantiation of WebDriver and setting up the capabilities for testing on the remote Selenium grid is added to the SetUp attribute. 

C#
 




xxxxxxxxxx
1
11


 
1
[SetUp]
2
public void Init()
3
{
4
   String username = "user-name";
5
   String accesskey = "access-key";
6
   String gridURL = "@hub.lambdatest.com/wd/hub";
7
 
8
   DesiredCapabilities capabilities = new DesiredCapabilities();
9
   ...................
10
   ...................
11
} 


Step 4 – The implementation of de-initialization remains unchanged and is included as a part of the TearDown attribute.

Shown below is the execution snapshot where it is observed that ParallelLTTests constructor is called four times, i.e., the number of times the TestFixture was instantiated by the NUnit framework.

Summary

In this blog, we had a look at some of the widely used attributes in the NUnit framework that are used for test parameterization, including TestFixture NUnit. Apart from the attributes that we covered in the blog, there are other attributes that aid in creating parameterized tests in NUnit framework. However, many of those NUnit attributes are not useful for test scenarios related to cross-browser testing or automated browser testing.

Cross-browser testing on the local Selenium grid is not scalable; hence, it is recommended to perform automated browser testing on a remote Selenium grid. When choosing an attribute for an NUnit parameterized test, you should also look at the complexities involved in adding/removing test cases. To summarize, NUnit parameterized tests are extremely useful in cutting down duplication in tests that can unnecessarily bloat the test code’s size.

I hope the NUnit parameterized test example I have showcased above will help make a difference in your test strategies!

Happy testing!

Testing NUnit Attribute (computing) Data Types

Published at DZone with permission of Himanshu Sheth. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • Munit: Parameterized Test Suite
  • Error Handling Inside Kumologica Subflow
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!