2019 / OCTOBER / 22


TestNGDataprovider

How to use TestNG Parameter and Dataprovider


How to use TestNG Parameter and Dataprovider

Hello everyone, in this blog post,we will be discussing what and why of TestNG Parameters. All you must be aware of what is parameterization and why it is important. Parameterization is a very important component during Development and Testing. Parameterization promotes the idea of Reusability. Reusability, What that means? Let's Look at an example-

Suppose we want to write a code to add 2 numbers. Numbers can be an integer or floating-point. Where you can use permutation to generate several different combinations like :

  1. The first number is a floating-point and the second number is an integer
  2. The first number is integer second is floating point
  3. Both are integer
  4. Both are floating-point.

Thus, instead of writing so many methods, we can simply write a single method where parameters are passed dynamically.
Similar is the case for testing where Parameterizations helps us to run test case multiple numbers of times with different inputs and validation values. This concept is known as Data-Driven Testing.

Selenium webdriver is an automation framework rather than a ready to use the tool, so you cannot expect it to be prepared for use without putting any effort.

There are 2 ways that could figure out how to pass parameters to the test case:

  1. Storing the parameters in the Excel file.
  2. Another most commonly used method is to use TestNG. TestNG lets you pass parameters directly to the test methods using testng.xml.

How to Pass TestNG Parameters:

There are 2 ways to pass parameters:

  1. @Parameters Annotation: Use TestNG.xml file to pass the simple parameter by value
  2. @DataProviders Annotation: Use Data Providers to pass complex parameters

Let's discuss all of the above 2 methods one by one.

  1. @Parameters Annotation: Use TestNG.xml to pass Parameters by Value:

    a. Launch Eclipse and Create a New Java Project by File->New->Java Project. For this example, I have named the project “SampleTestNG”.
    b. Right-click on the project->New->Package. This will let you create a new package. Name this package as “TestNGParameterization”.

    1

    2

    c. Right-click on the project “SampleTestNG”->New->Class. I have named the class file as “ParametersTesting”.

    3

    d. Now add the following code to the Class file created in the above step:

            package TestNGParameterization;
            import org.testng.annotations.Parameters;
            import org.testng.annotations.Test;
            public class ParametersTesting {
                @Parameters({ "BrowserName" })
                @Test
                public void OpenBrowser(String BrowserName) {
                    System.out.println("Parameter for Browser Passed is :- " + BrowserName);
                }
                @Parameters({ "WebsiteName" })
                @Test
                public void OpenWebsite(String WebsiteName) {
                    System.out.println("Parameter for Website Passed is :- " + WebsiteName);
                }
                @Parameters({ "UserName", "Password" })
                @Test
                public void FillLoginForm(String UserName, String Password) {
                    System.out.println("Parameter for User Name Passed is :- " + UserName);
                    System.out.println("Parameter for Password Passed is :- " + Password);
                }
            }

    We have created 3 methods in the Java Class file:

    1. OpenBrowser(): This method will take an argument specifying the browser to be used.
    2. OpenWebsite(): This method will take an argument specifying the website to launch.
    3. FillLoginForm(): This method will take 2 arguments specifying the username and password to be used to login to the website.

    e. Right-click the Class file “ParametersTesting”->TestNG->Convert To TestNG.

    4

    f. This step will generate the “TestNG.xml” file.

    5

    g. Add the following code to the xml file.

            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
            <suite name="Suite">
            <test thread-count="5" name="Test">
            </test> <!-- Test -->
            <test name="Parameters Testing">
            <parameter name="BrowserName" value="Firefox"/>
            <parameter name="WebsiteName" value="https://www.frugaltesting.com/"/>
            <parameter name="UserName" value="FrugalTesting"/>
            <parameter name="Password" value="AdminFrugalTesting"/>
            <classes>
            <class name="TestNGParameterization.ParametersTesting" />
            </classes>
            </test>
            </suite> <!-- Suite -->

    We have specified the values of the parameters in the xml file. Thus, you can see we are passing the parameters by value here using the testng.xml file.

    h. Right click the xml file->Run As->TestNG Suite.

    6

  1. @DataProvider Annotation: Use Data Provider to pass Complex Parameters
    When you need to pass complex parameters or to pass the parameters that are created from Java, we create a complex object or objects read from a property file or database, in such case, parameters are not passed using testng.xml. They need to be passed using Data Providers.
    Data Provider is a method annotated with @DataProvider. A Data Provider returns an array of objects.

    Features of DataProvider Annotation:

    1. DataProvider Annotation returns a 2-d list of objects.
    2. The test will be written for each set of object specified by the data provider object. Suppose the DataProvider object has 10 sets of more usage of objects in the sentence, so the test will run 10 times.
    3. The DataProvider Annotation has one attribute name Not clear. If you don’t specify or forgot to specify the name, in that case, the name of the method becomes the default choice.

Steps to Follow:

  1. Right-click on the package “TestNGParameterization” created in the @Parameters Annotation section. Click on New->Class. Name this Class file as “DataProviderTesting”.

  2. Add the following code to the Class file:

        package TestNGParameterization;
        import org.testng.Assert;
        import org.testng.annotations.BeforeMethod;
        import org.testng.annotations.DataProvider;
        import org.testng.annotations.Test;
    
        public class DataProviderTesting {
                // Even Number Test
                public class EvenNumber {
                    public Boolean validate(int number) {
                        return (number % 2 == 0 ? true : false);
                    }
                }
    
                private EvenNumber evennum;
    
                public void initialize() {
                    evennum = new EvenNumber();
                }
    
                @DataProvider(name = "EvenNumberTest")
                public static Object[][] getNumbers() {
                    return new Object[][] { { 1, false }, { 50, true }, { 10, true },{ 3, false }, { 55, false }, { 7, false }, { 22, true }, { 4, true }, { 101, false }, { 200, true } };
                }
    
                // This test will run 10 times as we are passing 10 parameters.
                @Test(dataProvider = "EvenNumberTest")
                public void testEvenNumberChecker(Integer inputNumber, Boolean expectedResult) {
                    System.out.println(inputNumber + " " + expectedResult);
                    Assert.assertEquals(expectedResult, evennum.validate(inputNumber));
                }
        }

    a. Here our aim is to check whether the number specified is an even number or not.
    b. For this, we have specified a list of data objects, specifying the number and expected result as True or False.
    c. We have user assert.equals() to check whether the expected result matches the actual value. The actual value is estimated using the Conditional Operator ?:

  3. Right-click “DataProviderTesting.java” Class file->TestNG->Convert to TestNG.

  4. Edit the code of the testng.xml file as follows:

        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
        <suite name="Suite">
        <test thread-count="5" name="Test">
        <classes>
        <class name="TestNGParameterization.DataProviderTesting"/>
        </classes>
        </test> <!-- Test -->
        </suite> <!-- Suite -->
  5. Right-click testng.xml file->Run As->TestNG Suite.

7

I hope with this blog post, you must have understood how to use different Annotations to pass Parameters using TestNG. We will be back with some interesting facts and coding examples. Till then, Stay Tuned and Keep Practicing.

Happy Coding!!!

Share:


Recommended Posts