TestNG Tutorials 57: DataProvider in TestNG – Passing External Data File Name to DataProvider Method Using TestNG xml

In last post, we have learnt how can we make parameterized DataProvider method in TestNG to provide test data to multiple Test methods from single DataProvider method. Let’s make it more customised.

Suppose you need to read data from external file like Excel, properties file etc in a DataProvider method. The name of external file is not constant and keep changing or you may need to pass different data sheet for execution. If external data files names are fixed , you can hard code it within script by following approach discussed in previous post. But if external data files name are not constant, you should not hard code within script.

To achieve this, we will mix concept of parameter from testng xml and DataProvider. Let’s learn it.

A DataProvider method can take an attribute of type ITestContext which can be used to read parameter value from testng xml. We will pass required data file name from testng xml to DataProvider method. If data file name changes, we can update it in testng xml. No need to make any changes in DataProvider methods.

Java Code:

TestNG xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<parameter name="DataFileforA" value="methodA.xlsx" />
<parameter name="DataFileforB" value="methodB.xlsx" />
<parameter name="DataFileforC" value="methodC.xlsx" />
  <test thread-count="5" name="Test">
      <class name="DataProvider.CustomDataProviderWithParameter"/>
  </test> <!-- Test -->
</suite> <!-- Suite -->


[RemoteTestNG] detected TestNG version 6.14.2
DatafileName for method A is methodA.xlsx
DatafileName for method B is methodB.xlsx
DatafileName for method C is methodC.xlsx

Total tests run: 3, Failures: 0, Skips: 0

Hope, you can implement above logic and leverage more advantages of DataProvider methods.

More about TestNG in upcoming posts. Stay tuned.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning