TestNG DataProvider Read Test Data From Xml File

DataProvider is used to pass numerous data sets to a test method in TestNG. This can improve test efficiency greatly. In this article we will tell you how to read data from Xml file in dataprovider. We will also tell you how to easily maintain and edit a xml file. What ever data source you use, you should first make sure that the data type and size in dataprovider returned array should match the parameters type and size of the test method in TestNG.   

Read Testing Data From Xml File

Generate Test Data Xml File

People always think xml file is not good for edit. But we found below method to make it easy to edit a xml file.

  1. Download OpenOffice and install it. It is open source and free.
  2. Choose SpreadSheet when open OpenOffice for the first time.
    choose spreadsheet when open openoffice
  3. Input below test data in the spreadsheet.
    test data in spread sheet
  4. Save the file as userAccount.ods. Please note do not export it to xml directly, because maybe that action can cause your PC hanged.
    save test data to userAccount.ods file
  5. Because .ods is just zip format then you can change it’s extension to zip. Then the file name is changed to userAccount.zip. Unzip it to a local folder. There is a content.xml in that folder. It is just where the test data you entered exist.
    content.xml store test data

Read Test Data From content.xml

We will read test data from above generated content.xml in below example. We use TestNG in below example also.

Steps:

  1. Change the source extension from .ods to .zip.
  2. Get the content.xml in above zip file.
  3. Parse content.xml and return test data in it.
  4. Rename extension from .zip back to .ods.
    Because there is a bug in current website, so we have to split a long java method into two part as below. Sorry for inconvenience. You can download the attachment to see java source code.

    	  @DataProvider
    	  /* Read from content.xml. */
    	  public Object[][] xmlFileDataProvider() throws IOException {
    		  Object[][] retDataArr = null;
    		  
    		  /* Get source .ods document and change it's extension to a .zip.*/
    		  String srcFilePath = "C:/WorkSpace/dev2qa.com/Doc/Passing JUnit DataProvider Test Data From Xml Or Excel sheet/userAccount.ods";
    		  int dotLastIdx = srcFilePath.lastIndexOf(".");
    		  String srcZipFilePath = srcFilePath.substring(0, dotLastIdx) + ".zip";
    		  File srcFile = new File(srcFilePath);
    		  srcFile.renameTo(new File(srcZipFilePath));
    		  
    		  /* Read the content.xml. */
    		  ZipFile zFile = new ZipFile(srcZipFilePath);
    		  Enumeration<? extends ZipEntry> zEntries = zFile.entries();
    		  while(zEntries.hasMoreElements()){
    		        ZipEntry zEntry = zEntries.nextElement();
    		        String zEntryName = zEntry.getName();
    		        
    		        if(zEntryName.endsWith("content.xml"))
    		        {
    		        	 InputStream stream = zFile.getInputStream(zEntry);
    		        	 /* Parse the stream and return the test data then break.*/
    		        	 retDataArr = this.parseXmlStream(stream);
    		        	 stream.close();
    		        	 break;
    		        }   
    		  }
    		  zFile.close();
    		  
    		  /* Rename the .zip document back to original .ods document . */
    		  File srcZipFile = new File(srcZipFilePath);
    		  srcZipFile.renameTo(new File(srcFilePath));
    		  
    		  return retDataArr;
    	  }
    	  /* Parse the test data from content.xml input stream. */
    	  private Object[][] parseXmlStream(InputStream xmlInputStream)
    	  {
    		  List<List<String>> testDataList = new ArrayList<List<String>>();
    		  if(xmlInputStream!=null)
    		  {
    			  try
    			  {
    				  DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory.newInstance();
    				  DocumentBuilder domBuilder = domBuilderFactory.newDocumentBuilder();
    				  Document document = domBuilder.parse(xmlInputStream);
    				  
    				  /* Get table list. */
    				  NodeList nodeList = document.getElementsByTagName("table:table");
    				  
    				  if(nodeList!=null)
    				  {
    					  int nlSize = nodeList.getLength();
    					  for(int i=0;i<nlSize;i++)
    					  {
    						  Node node = nodeList.item(i);
    						  NamedNodeMap nodeMap = node.getAttributes();
    						  
    						  String tableName = nodeMap.getNamedItem("table:name").getNodeValue();
    						  
    						  //System.out.println("tableName = " + tableName);
    						  
    						  /* Get first spread Sheet where we store test data.*/
    						  if("Sheet1".equalsIgnoreCase(tableName))
    						  {
    							  NodeList cNodeList = node.getChildNodes();
    							  if(cNodeList!=null)
    							  {
    								  int cNodeListSize = cNodeList.getLength();
    								  
    								  for(int j=0;j<cNodeListSize;j++)
    								  {
    									  Node cNode = cNodeList.item(j);
    									  String cNodeName = cNode.getNodeName();
    									  
    									  /* Get each row in Sheet1. */
    									  if("table:table-row".equalsIgnoreCase(cNodeName))
    									  {
    										  NodeList cellNodeList = cNode.getChildNodes();
    										  if(cellNodeList!=null)
    										  {
    											  int cellNodeListSize = cellNodeList.getLength();
    											  if(cellNodeListSize >= 2)
    											  {
    												  Node userEmailNode = cellNodeList.item(0);
    												  Node passwordNode = cellNodeList.item(1);
    												  
    												  /* Add each row value to the list. */
    												  List rowList = new ArrayList<String>();
    												  rowList.add(userEmailNode.getTextContent());
    												  rowList.add(passwordNode.getTextContent());
    												  
    												  testDataList.add(rowList);
    											  }
    										  }
    									  }
    								  }
    							  }
    						  }
    					  }
    				  }
    			  }catch(Exception ex)
    			  {
    				  ex.printStackTrace();
    			  }
    		  }
    		  
    		  /* Translate the list to an array.*/
    		  int listSize = testDataList.size();
    		  
    		  String[][] retDataArr = new String[listSize][2];
    		  
    		  for(int i=0;i<listSize;i++)
    		  {
    			  List<String> rowList = testDataList.get(i);
    			  retDataArr[i][0] = rowList.get(0);
    			  retDataArr[i][1] = rowList.get(1);
    		  }
    		  
    		  return retDataArr;
    	  }

xml data in content.xml

Use DataProvider  In TestNG

We will use dataprovider in a test method testXmlDataProvider(String userName, String password). Please note the input parameter, the type and number of parameters should match the dataprovider returned array.

READ :   Use Selenium Webdriver To Select Options From DropDown List

Test Case Steps:

  1. Open a local login.html.
  2. Input the userName and password in the login form.
  3. Click submit button.
	  @Test(dataProvider = "xmlFileDataProvider")
	  public void testXmlDataProvider(String userName, String password) throws InterruptedException {
		  
		  System.out.println("Start test with data, userName = " + userName + " , password = " + password);
		  
		  this.ffDriver.get("file://C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/webdriver/dataprovider/login.html");
		  
		  By userNameById = By.id("userName");
		  By passwordById = By.id("password");
		  By submitById = By.id("submitBtn");
		  
		  this.ffDriver.findElement(userNameById).sendKeys(userName);
		  this.ffDriver.findElement(passwordById).sendKeys(password);
		  
		  Thread.sleep(3000);
		  
		  this.ffDriver.findElement(submitById).click();
	  }

The Firefox webdriver object will be created in the @BeforeClass method and destroyed in the @AfterClass method.

Download “TestNG-DataProvider-Read-Test-Data-From-Xml-File-Example-Code.zip” TestNG-DataProvider-Read-Test-Data-From-Xml-File-Example-Code.zip – Downloaded 99 times – 3 KB

(Visited 1,769 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.