How to write Nunit Parameterized Test
On This Page What Is Parameterization in NUnit?
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. 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: Below are the key reasons why Parameterization in NUnit is important: 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: There are Four ways to group the parameter and can be legislate to the test in Nunit Read More: 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 For example, 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. We incur these values as input parameter for our test method when Nunit lam, hence we declare two parameter for our test method And now you can use these parameters in our code where the code clicks on the model and control the substance In this way, you can reuse our exam for various datasets. 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 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. 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 The tests will be divided into In this proficiency, the Nunit allows you to pass Random Attribute Array with 1 to 3 parameters Syntax: 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 Nunit generates test with below combination 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. 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 In this technique, Nunit allows us to pass named data germ at test method parameter level using attribute[ValueSource]. As observed, theuserDataobjective now is employ to the exam method ’ s parameter. Nunit will render tests like below Running NUnit parameterized tests on BrowserStack ’ s cloud infrastructure enable seamless cross-browser and cross-device establishment, secure robust test coverage. Read More: on Integration between BrowserStack, NUnit & amp; Selenium. 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. On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.How to write Nunit Parameterized Test
What Is Parameterization in NUnit?
Importance of Parameterization In NUnit
How to indite Nunit Parameterized Test
Parameterization techniques in NUnit
Inline & # 8211; As Test Case Attribute
[TestCase (“ input1 ”, “ input2 ”)]
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 ();}}}[TestCase (`` OnePlus '', `` 6 Product (s) found. '')] [TestCase (`` Google '', `` 3 Product (s) institute. '')]
public void NunitSeleniumTest (String model, String message)
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 ();Inline Parameterization Using Random, Range, and Values Attributes
Range Attribute
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
[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);}Random Attribute
Random (int count) Random (int minNumber, int MaxNumber, int reckoning)
[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);}Separate & # 8211; TestCaseSource Attribute
[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 ''}};Separate & # 8211; ValueSource Attribute
[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 ''}};Integrating NUnit Selenium Tests with BrowserStack
Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously