Deepak543
Deepak543

Reputation: 33

How to run the same code for multiple input files in TestNG framework?

My test class has some code which does the desired validation.

Test Class:

@Parameters({ "InputFile01"})
@Test
public void testCase01(String InputFile01) {
  //Code xyz
}

@Parameters({ "InputFile02"})
@Test
public void testCase01(String InputFile02) {
  //Code xyz (Same code as above)
}

I have to copy above code multiple times to run it for different input files, How do I handle this

I am running test suit from xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Regression">

<test name="PI01_Sprint1_ID12345">

        <classes>
            <class name="org.PI01.PI01_Sprint1_ID12345">
                <methods>
                    <parameter name="InputFile01" value="PI01\TC01.xml" />
                    <include name="testCase01" />
                     <parameter name="InputFile02" value="PI01\TC02.xml" />
                    <include name="testCase02" />

                </methods>
            </class>
        </classes>
    </test>

</suite>

Upvotes: 1

Views: 431

Answers (1)

Mikhail Antonov
Mikhail Antonov

Reputation: 1367

You don't need to repeat the code with parameterized test, that's what it's invented for :)

The correct usage in your case seems to be:

@Parameters({ "filename"})
@Test
public void testCase01(String filename) {
  //openFile(filename)
  //do something
}

And in config call test with different values of this parameter:

<test name="test file1">
    <parameter name="filename" value="file1.txt" />
...    
</test>
<test name="test file2">
    <parameter name="filename" value="file2.txt" />
 ...    
</test>

And it seems you can provide a set of parameters using DataProviders:

public class TestParameterDataProvider {

    @Test(dataProvider = "provideFilenames")
    public void test(String filename) {
        //openFile(filename)
        //assert stuff...
    }

    @DataProvider(name = "provideFilenames")
    public String[] provideData() {
        return new String[] { 
            "filename1", "filename2", "filename3" 
        };
    }

}

More: https://www.tutorialspoint.com/testng/testng_parameterized_test.htm

https://www.mkyong.com/unittest/testng-tutorial-6-parameterized-test/

Upvotes: 1

Related Questions