Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Write Selenium Web Driver Test Result To XML File

In some cases, test engineers need to export or save Selenium WebDriver test result in XML file format.  In this example below, I will explain how to write test results as a xml file. 

in this example, the test result is written as a file named "TestResult.xml". 

Login Test Case:

1. Go to http://www.seleniummaster.com/seleniummastertestapp/index.php
2. Enter "test" in the Username field
3. Enter "XXXX" in the Password filed
4. Click on the Login button
5. Verify that the text "Selenium Test" is present.

Step 1: on Eclipse, create a Java Project called SeleniumMasterLoginTestXmlExport. Add a package named com.seleniummaster.testresultXmlproject and then add three classes as listed below:

  • LoginTest class (this is a TestNG class)
  • TestCases class (this class has object definition for test cases like test case id, test case name and test case status
  • TestResultXmlUtility class (this class creates xml file)

and also, in the build path, add Selenium libraries and Apache Pdfbox library as reference jar files. 

 

 

Step 2: write the code in the TestCases.java class

 
package com.seleniummaster.TestResultXmlProject;
public class TestCases {
//test case Id string
private String testCaseId;
//test case name string
private String testCaseName;
//test result status string
private String TestCaseResultStatus;
//construct a test case object
public TestCases(String testcaseid, String testcasename, String testresultstatus)
{
  this.setTestCaseId(testcaseid);
  this.setTestCaseName(testcasename);
  this.setTestCaseResultStatus(testresultstatus);
}
/**
 @return the testCaseResultStatus
 */
public String getTestCaseResultStatus() {
  return TestCaseResultStatus;
}

/**
 @param testCaseResultStatus the testCaseResultStatus to set
 */
public void setTestCaseResultStatus(String testCaseResultStatus) {
  TestCaseResultStatus = testCaseResultStatus;
}

/**
 @return the testCaseName
 */
public String getTestCaseName() {
  return testCaseName;
}

/**
 @param testCaseName the testCaseName to set
 */
public void setTestCaseName(String testCaseName) {
  this.testCaseName = testCaseName;
}

/**
 @return the testCaseId
 */
public String getTestCaseId() {
  return testCaseId;
}

/**
 @param testCaseId the testCaseId to set
 */
public void setTestCaseId(String testCaseId) {
  this.testCaseId = testCaseId;
}

/**
   @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

  }

}

Step 3: write the following code in the TestResultXmlUtility.java class

package com.seleniummaster.TestResultXmlProject;
import java.io.File;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
import org.w3c.dom.Document;

public class TestResultXmlUtility {
  
private static DocumentBuilderFactory factory;
private static DocumentBuilder builder;
private static Document doc;
  /**
   @param args
   @throws ParserConfigurationException 
   */
  public void WriteTestResultToXml(String filename,List<TestCases> itemsthrows ParserConfigurationException
  {
  Date timeStamp = new Date();
    try{
  //define an empty document
     factory = DocumentBuilderFactory.newInstance();
    builder = factory.newDocumentBuilder();
    doc = builder.newDocument();
    //root element
    Element testReportElement=doc.createElement("TestReport");
    testReportElement.setAttribute("time", timeStamp.toString());
    doc.appendChild(testReportElement);
    //Test Cases Element
    Element testCasesElement=doc.createElement("TestCases");
    testReportElement.appendChild(testCasesElement);
    //For each test case object add a Test Case Element in the xml file
    for(TestCases a:items)
    {
    Element testCaseElement=doc.createElement("TestCase");
    testCaseElement.setAttribute("id", a.getTestCaseId());
    testCasesElement.appendChild(testCaseElement);
    // Name element
    Element name = doc.createElement("Name");
    name.appendChild(doc.createTextNode(a.getTestCaseName()));
    testCasesElement.appendChild(name);
    // Test Result  element
    Element testResult = doc.createElement("TestResult");
    testResult.appendChild(doc.createTextNode(a.getTestCaseResultStatus()));
    testCasesElement.appendChild(testResult);
    }
    // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
          transformer.setOutputProperty(OutputKeys.METHOD,"xml");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filename));
     
        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);
     
        transformer.transform(source, result);
     
        System.out.println("File saved!");
     
       catch (ParserConfigurationException pce) {
        pce.printStackTrace();
        catch (TransformerException tfe) {
        tfe.printStackTrace();
        }
      }
  }

Step 4: write the following code in the LoginTest.java class

package com.seleniummaster.TestResultXmlProject;
import static org.testng.AssertJUnit.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class LoginTest {
//define a WebDriver named driver
 private WebDriver driver;
 //create a new instance of Test Result Xml Utility Object
 TestResultXmlUtility testResultXmlUtility=new TestResultXmlUtility();
 //create a list object that will contain number of test cases
 List<TestCases> testcases=new ArrayList<TestCases>();

 //login test
  
 @Test
  public void SeleniumMasterLoginTest() {
{
      //open login page
        driver.navigate().to("http://www.seleniummaster.com/seleniummastertestapp/index.php");
        //maximize the window
      driver.manage().window().maximize();
      //type in user name 
      driver.findElement(By.id("login_login_username")).sendKeys("test");
      //type in user password
      driver.findElement(By.id("login_login_password")).sendKeys("XXXX")//here password is omitted
      //click on the submit button
     driver.findElement(By.id("login_submit")).click();
     //within 60 seconds try asserting that user logged on
       for (int second = 0;; second++) {
        if (second >= 60Assert.fail("timeout");
        try 
          assertEquals("Online users", driver.findElement(By.cssSelector("#sb-onlineusers > h3")).getText());
          //add test case to the testcases list as pass
          testcases.add(new TestCases("002","Login Test","Pass"));
          break;
     
        catch (Exception e) {
          //add test case to the testcases list as Fail
          testcases.add(new TestCases("002","Login Test","Fail"));
        }
           }
         
      }
  }
  @BeforeMethod
  public void Setup() {
//add test result header information to the resultList
try
{
  //initialize Firefox driver
  driver=new FirefoxDriver();
  //obtain windows handler name
  String windowsHandle=driver.getWindowHandle();
  //assert that a window has been launched
  assertEquals(true, windowsHandle.length()>0);
  //add a test case to the testcases list as pass
    testcases.add(new TestCases("001","Test Setup ","Pass"));
}
catch(Exception e)
{
  ////add a test case to the testcases list as Fail
    testcases.add(new TestCases("001","Test Setup ","Fail"));  
}
 
   }
  @AfterMethod
  public void TearDown() throws IOException, ParserConfigurationException {
  //close the driver
 driver.close();
 //write the test result to xml file with file name TestResult
 testResultXmlUtility.WriteTestResultToXml("TestResult.xml", testcases);
  //quit the driver
 driver.quit();
  }

}

Step 5: create a testng.xml file as shown below and right click on it and select Run As "TestNG Suite"

 <?xml version="1.0" encoding="UTF-8"?>

<suite name="Suite" parallel="false">
<test name="LoginTest">
<classes>
<class name="com.seleniummaster.TestResultXmlProject.LoginTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Step 6: open the TestResult.xml file. The file shows that Test Setup and Login Test passed. You can also see the result in the TestNG "test-output" table.