This Blog gives good knowledge of core java concepts and selenium (Automation Testing Tool). It also includes some topics of MAVEN (Build Tool) , Jenkins (Continuous Integration Tool) and Cucumber (Behavior Driven Development)
Tuesday, 3 November 2015
Basic Selenium functions with C#
Basic Selenium functions with C#
Sample Script for Framework:
public OpenQA.Selenium.IWebDriver iWebDriver; public static int isloggedin = 0; public StreamWriter sw; public string desc; public string mode; public IWebDriver StartTest() { if (isloggedin == 0) { iWebDriver = new FirefoxDriver(); iWebDriver.Manage().Window.Maximize(); login(); isloggedin = 1; } return iWebDriver; } public int RandomNumber() { Random r = new Random(); return r.Next(1, 1000); } public void login() { iWebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(300)); iWebDriver.Navigate().GoToUrl(dataFile("URL")); // Enter user name iWebDriver.FindElement(By.Id("txtEmail")).Clear(); iWebDriver.FindElement(By.Id("txtEmail")).SendKeys(dataFile("UserName")); System.Threading.Thread.Sleep(5); // Enter password iWebDriver.FindElement(By.Id("txtPassword")).Clear(); iWebDriver.FindElement(By.Id("txtPassword")).SendKeys(dataFile("Password")); // Click Submit button iWebDriver.FindElement(By.Id("lnkSubmit")).Click(); System.Threading.Thread.Sleep(5000); }
Sample Script for Framework:
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using System.Threading; using System.IO; namespace SeleniumTest { public class TC_001 : Logging { public String startTime; public String endTime; public String status; Logging c1 = new Logging(); public void CreateUser(IWebDriver WebDriver) { startTime = DateTime.Now.ToString(); if (excel(this.GetType().Name).Equals("Y")) { WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(420)); try { Executionlog(DateTime.Now.ToString(), module(this.GetType().Name), this.GetType().Name, "Starting Test"); WebDriver.Navigate().GoToUrl("Example Website"); WebDriver.FindElement(By.XPath("//a[contains(text(),'NEW CONTACT')]")).Click(); WebDriver.FindElement(By.Id("new-contact")).Click(); System.Threading.Thread.Sleep(5000); new SelectElement(WebDriver.FindElement(By.Id("newcontact-location"))).SelectByIndex(1); WebDriver.FindElement(By.XPath("//input[@title='FIRST NAME']")).Clear(); WebDriver.FindElement(By.XPath("//input[@title='FIRST NAME']")).SendKeys("Tony" + RandomNumber()); WebDriver.FindElement(By.XPath("//input[@title='LAST NAME']")).Clear(); WebDriver.FindElement(By.XPath("//input[@title='LAST NAME']")).SendKeys("Stark" + RandomNumber()); WebDriver.FindElement(By.XPath("//a[text()='Finish']")).Click(); System.Threading.Thread.Sleep(5000); WebDriver.FindElement(By.XPath("//a[text()='Customer Info']")).Click(); Executionlog(DateTime.Now.ToString(), module(this.GetType().Name), this.GetType().Name, "Customer Created Successfully"); System.Threading.Thread.Sleep(5000); status = "Pass"; } catch (Exception e) { endTime = DateTime.Now.ToString(); status = "Fail"; ErrorLog(DateTime.Now.ToString(), module(this.GetType().Name), this.GetType().Name, e.StackTrace.ToString()); } if (status.Equals("Pass")) { status = "Pass"; } else { status = "Fail"; } endTime = DateTime.Now.ToString(); Executionlog(DateTime.Now.ToString(), module(this.GetType().Name), this.GetType().Name, status); addSummary(startTime, endTime, description(this.GetType().Name), module(this.GetType().Name), this.GetType().Name, status); } else { endTime = DateTime.Now.ToString(); Executionlog(DateTime.Now.ToString(), module(this.GetType().Name), this.GetType().Name, "Not Executed"); addSummary(startTime, endTime, description(this.GetType().Name), module(this.GetType().Name), this.GetType().Name, "Not Executed"); } } } }
C# Important Functions:
Important namespaces used:
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; using Microsoft.Office.Interop.Excel; using System.Drawing; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using System.Threading; using System.Configuration; using System.Globalization;
Function to Create Result:
public void createResult(string StartTime) { Microsoft.Office.Interop.Excel.Application TestLog = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook TestLogFile = TestLog.Workbooks.Add(); Microsoft.Office.Interop.Excel.Worksheet Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Logs.Name = string.Format("Test Results"); Logs.Cells[1, 1] = "Test Execution Results – (ABC)"; Logs.Cells[1, 6] = string.Format("Start Time: {0}", StartTime.ToString()); Logs.Cells[3, 1] = "Test Module"; Logs.Cells[3, 2] = "Test Case Id"; Logs.Cells[3, 3] = "Test Case Description"; Logs.Cells[3, 4] = "Start Time"; Logs.Cells[3, 5] = "End Time"; Logs.Cells[3, 6] = "Result"; Microsoft.Office.Interop.Excel.Range R1 = Logs.get_Range("D1").EntireColumn; R1.NumberFormat = "MM/dd/yyyy hh:mm:ss AM/PM"; Microsoft.Office.Interop.Excel.Range R2 = Logs.get_Range("E1").EntireColumn; R2.NumberFormat = "MM/dd/yyyy hh:mm:ss AM/PM"; Logs.get_Range("A1", "E1").Interior.Color = System.Drawing.Color.SkyBlue; Logs.get_Range("A3", "F3").Interior.Color = System.Drawing.Color.Gainsboro; TestLogFile.SaveAs(@"C:\TestResults.xls"); TestLogFile.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(Logs); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLogFile); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLog); }
Function to add summary:
public void addSummary(string StartTime, string EndTime, string description,string TestPlanId, string TestCaseId, string Outcome) { Microsoft.Office.Interop.Excel.Application TestLog = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook TestLogFile = TestLog.Workbooks.Open(@"C:\TestResults.xls");//.Add(); Microsoft.Office.Interop.Excel.Worksheet Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range range = Logs.UsedRange; int colcount = range.Columns.Count; int rowcount = range.Rows.Count; Logs.Cells[rowcount + 1, 1] = TestPlanId; Logs.Cells[rowcount + 1, 2] = TestCaseId; Logs.Cells[rowcount + 1, 3] = description; Logs.Cells[rowcount + 1, 4] = string.Format("{0}", StartTime.ToString()); Logs.Cells[rowcount + 1, 5] = string.Format("{0}", EndTime.ToString()); Logs.Cells[rowcount + 1, 6] = Outcome; TestLogFile.Save(); TestLogFile.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(Logs); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLogFile); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLog); }
Function for Test Case End Time:
public void endTimefunction(string EndTime) { Microsoft.Office.Interop.Excel.Application TestLog = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook TestLogFile = TestLog.Workbooks.Open(@"C:\TestResults.xls");//.Add(); Microsoft.Office.Interop.Excel.Worksheet Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range range = Logs.UsedRange; Logs.Cells[2, 6] = string.Format("End Date Time: {0}", EndTime.ToString()); TestLogFile.Save(); TestLogFile.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(Logs); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLogFile); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLog); }
Function for Test Case Start Time:
public void startTimefunction(string startTime) { Microsoft.Office.Interop.Excel.Application TestLog = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook TestLogFile = TestLog.Workbooks.Open(@"C:\TestResults.xls");//.Add(); Microsoft.Office.Interop.Excel.Worksheet Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Logs = (Worksheet)TestLogFile.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range range = Logs.UsedRange; Logs.Cells[1, 6] = string.Format("Start Date Time: {0}", startTime.ToString()); TestLogFile.Save(); TestLogFile.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(Logs); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLogFile); System.Runtime.InteropServices.Marshal.ReleaseComObject(TestLog); }
Function for Execution Log:
public void Executionlog(string Time,string TestPlanId, string TestCaseId, string Message) { string filePath = @"C:\TestResults"; string file = string.Format(@"{0}\TP{1} - ExecutionLog {2}.txt", filePath, "Automation", DateTime.Now.ToString("MM-dd-yyyy")); FileInfo logFile = new FileInfo(file); StreamWriter log = logFile.AppendText(); string logMessage = string.Format(">> {0},TM: {1}, TC: {2}, {3} \n", Time,TestPlanId, TestCaseId, Message); log.WriteLine(logMessage); log.Flush(); log.Close(); }
Function for Error Log:
public void ErrorLog(string Time,string TestPlanId, string TestCaseId, string Message) { string filePath = @"C:TestResults"; string file = string.Format(@"{0}\TP{1}-TC{2} - ErrorLog {3}.txt", filePath, "Automation", TestCaseId, DateTime.Now.ToString("MM-dd-yyyy"));
FileInfo logFile = new FileInfo(file); StreamWriter log = logFile.AppendText(); string logMessage = string.Format(">> {0},TM: {1}, TC: {2} {3}\n",Time, TestPlanId, TestCaseId, Message); log.WriteLine(logMessage); log.Flush(); log.Close(); }
Function to read data from data file:
public string dataFile(string input) { Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; Microsoft.Office.Interop.Excel.Range xlrange; string URL="URL"; string UserName="UserName"; string Password="Password"; string result=""; int xlRowCnt = 2; xlApp = new Microsoft.Office.Interop.Excel.Application(); //Open Excel file xlWorkBook = xlApp.Workbooks.Open(@"C:\Data Sheet.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlrange = xlWorkSheet.UsedRange; //int abc = 1; if (input.Equals(URL)) { result = (string)(xlrange.Cells[xlRowCnt, 1] as Microsoft.Office.Interop.Excel.Range).Value2; } else if (input.Equals(UserName)) { result = (string)(xlrange.Cells[xlRowCnt, 2] as Microsoft.Office.Interop.Excel.Range).Value2; } else if (input.Equals(Password)) { result = (string)(xlrange.Cells[xlRowCnt, 3] as Microsoft.Office.Interop.Excel.Range).Value2; } xlWorkBook.Close(); return result; }
Function for Controller:
public string module(string TestCaseId) { Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; Microsoft.Office.Interop.Excel.Range xlrange; string xlString; string module = ""; int xlRowCnt = 0; xlApp = new Microsoft.Office.Interop.Excel.Application(); //Open Excel file xlWorkBook = xlApp.Workbooks.Open(@"C:\Controller.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlrange = xlWorkSheet.UsedRange; //int abc = 1; for (xlRowCnt = 1; xlRowCnt <= xlrange.Rows.Count; xlRowCnt++) { xlString = (string)(xlrange.Cells[xlRowCnt, 1] as Microsoft.Office.Interop.Excel.Range).Value2; if (xlString.Equals(TestCaseId)) { module = (string)(xlrange.Cells[xlRowCnt, 3] as Microsoft.Office.Interop.Excel.Range).Value2; } } xlWorkBook.Close(); return module; }
Function to read write from excel:
public string excel(string TestCaseId) { Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; Microsoft.Office.Interop.Excel.Range xlrange; string xlString; int xlRowCnt = 0; xlApp = new Microsoft.Office.Interop.Excel.Application(); //Open Excel file xlWorkBook = xlApp.Workbooks.Open(@"C:\Controller.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlrange = xlWorkSheet.UsedRange; for (xlRowCnt = 1; xlRowCnt <= xlrange.Rows.Count; xlRowCnt++) { xlString = (string)(xlrange.Cells[xlRowCnt, 1] as Microsoft.Office.Interop.Excel.Range).Value2; if (xlString.Equals(TestCaseId)) { mode = (string)(xlrange.Cells[xlRowCnt, 4] as Microsoft.Office.Interop.Excel.Range).Value2; //Console.WriteLine(mode); } } xlWorkBook.Close(); return mode; }
Function to add description to result file:
public string description(string TestCaseId) { Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; Microsoft.Office.Interop.Excel.Range xlrange; string xlString; string desc=""; int xlRowCnt = 0; xlApp = new Microsoft.Office.Interop.Excel.Application(); //Open Excel file xlWorkBook = xlApp.Workbooks.Open(@"C:\QQ Catalyst Project\Controller Sheet\Controller.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlrange = xlWorkSheet.UsedRange; for (xlRowCnt = 1; xlRowCnt <= xlrange.Rows.Count; xlRowCnt++) { xlString = (string)(xlrange.Cells[xlRowCnt, 1] as Microsoft.Office.Interop.Excel.Range).Value2; if (xlString.Equals(TestCaseId)) { desc = (string)(xlrange.Cells[xlRowCnt, 2] as Microsoft.Office.Interop.Excel.Range).Value2; } } xlWorkBook.Close(); return desc; }
end...
Thursday, 15 October 2015
Program to capture screenshot
* For JAVA Project add jars for selenium.
* For Maven Project, add Dependency for selenium
* For Maven Project, add Dependency for selenium
import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class captureScreenshot { public WebDriver drv; public void screenshot(WebDriver drv, String fileName) throws Exception { File screenshot = ((TakesScreenshot)drv).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File(fileName)); } public void executeScript() throws Exception{ drv=new FirefoxDriver(); drv.manage().window().maximize(); drv.navigate().to("https://www.google.com/"); screenshot(drv, "D:\\google.png"); drv.close(); } public static void main(String[] args) { captureScreenshot c1=new captureScreenshot(); try { c1.executeScript(); } catch (Exception e) { e.printStackTrace(); } } }
Adding csv Logger to Selenium Project
* For JAVA Project add jars for csv.
* For Maven Project, add Dependency for csv:
* For Maven Project, add Dependency for csv:
<dependency> <groupId>net.sf.opencsv</groupId> <artifactId>opencsv</artifactId> <version>2.3</version> </dependency>
Program for csv logger:
We have created two logs.
*Simple Log
*Error Log
package ProjectInputOutput.Files; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import au.com.bytecode.opencsv.CSVWriter; public class csvLogsProgram { public CSVWriter writeLog; public CSVWriter writeErrLog; public static List<String[]> logs = new ArrayList<String[]>(); public static List<String[]> errLogs = new ArrayList<String[]>(); public void writeLog(List<String[]> logResult)throws Exception{ try{ writeLog = new CSVWriter(new FileWriter("D:\\log.csv")); writeLog.writeAll(logResult); writeLog.close(); } catch(Exception e){ e.printStackTrace(); throw e; } } public void writeErrLog(List<String[]> logResult)throws Exception{ try{ writeErrLog = new CSVWriter(new FileWriter("D:\\errorLog.csv")); writeErrLog.writeAll(logResult); writeErrLog.close(); } catch(Exception e){ e.printStackTrace(); throw e; } } public static void main(String [] args) { logs.add(new String[]{"Starting "+" at "+new Date(),"","Pass"}); errLogs.add(new String[]{"Starting "+" at "+new Date(),"","Fail"}); csvLogsProgram io=new csvLogsProgram(); try { io.writeLog(logs); io.writeErrLog(errLogs); } catch (Exception e) { e.printStackTrace(); } } }
Adding csv Logger to Selenium Project
* For JAVA Project add jars for csv.
* For Maven Project, add Dependency for csv:
* For Maven Project, add Dependency for csv:
<dependency> <groupId>net.sf.opencsv</groupId> <artifactId>opencsv</artifactId> <version>2.3</version> </dependency>
Program for csv logger:
We have created two logs.
*Simple Log
*Error Log
package ProjectInputOutput.Files; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import au.com.bytecode.opencsv.CSVWriter; public class csvLogsProgram { public CSVWriter writeLog; public CSVWriter writeErrLog; public static List<String[]> logs = new ArrayList<String[]>(); public static List<String[]> errLogs = new ArrayList<String[]>(); public void writeLog(List<String[]> logResult)throws Exception{ try{ writeLog = new CSVWriter(new FileWriter("D:\\log.csv")); writeLog.writeAll(logResult); writeLog.close(); } catch(Exception e){ e.printStackTrace(); throw e; } } public void writeErrLog(List<String[]> logResult)throws Exception{ try{ writeErrLog = new CSVWriter(new FileWriter("D:\\errorLog.csv")); writeErrLog.writeAll(logResult); writeErrLog.close(); } catch(Exception e){ e.printStackTrace(); throw e; } } public static void main(String [] args) { logs.add(new String[]{"Starting "+" at "+new Date(),"","Pass"}); errLogs.add(new String[]{"Starting "+" at "+new Date(),"","Fail"}); csvLogsProgram io=new csvLogsProgram(); try { io.writeLog(logs); io.writeErrLog(errLogs); } catch (Exception e) { e.printStackTrace(); } } }
Adding csv Logger to Selenium Project
* For JAVA Project add jars for csv.
* For Maven Project, add Dependency for csv:
* For Maven Project, add Dependency for csv:
<dependency> <groupId>net.sf.opencsv</groupId> <artifactId>opencsv</artifactId> <version>2.3</version> </dependency>
Program for csv logger:
package ProjectInputOutput.Files; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import au.com.bytecode.opencsv.CSVWriter; public class csvLogsProgram { public CSVWriter writeLog; public CSVWriter writeErrLog; public static List<String[]> logs = new ArrayList<String[]>(); public static List<String[]> errLogs = new ArrayList<String[]>(); public void writeLog(List<String[]> logResult)throws Exception{ try{ writeLog = new CSVWriter(new FileWriter("D:\\log.csv")); writeLog.writeAll(logResult); writeLog.close(); } catch(Exception e){ e.printStackTrace(); throw e; } } public void writeErrLog(List<String[]> logResult)throws Exception{ try{ writeErrLog = new CSVWriter(new FileWriter("D:\\errorLog.csv")); writeErrLog.writeAll(logResult); writeErrLog.close(); } catch(Exception e){ e.printStackTrace(); throw e; } } public static void main(String [] args) { logs.add(new String[]{"Starting "+" at "+new Date(),"","Pass"}); errLogs.add(new String[]{"Starting "+" at "+new Date(),"","Fail"}); csvLogsProgram io=new csvLogsProgram(); try { io.writeLog(logs); io.writeErrLog(errLogs); } catch (Exception e) { e.printStackTrace(); } } }
Monday, 17 August 2015
Creating PDF Report using TestNG with Selenium
There are two steps:
1. First Create JyperionListener.java
2. Then use JyperionListener.java in any TestNG class (like we have developed google.java)
1. Create class JyperionListener.java
2. Use JyperionListener.java in TestNG class, find below code of TestNG class:
1. First Create JyperionListener.java
2. Then use JyperionListener.java in any TestNG class (like we have developed google.java)
1. Create class JyperionListener.java
package reporting; import java.awt.Color; import java.io.FileOutputStream; import java.util.Date; import java.util.HashMap; import java.util.Random; import java.util.Set; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import reusable.Base; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfAction; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; public class JyperionListener implements ITestListener { /** * Document */ private Document document = null; /** * PdfPTables */ PdfPTable successTable = null, failTable = null; /** * throwableMap */ private HashMap<Integer, Throwable> throwableMap = null; /** * nbExceptions */ private int nbExceptions = 0; public JyperionListener() { log("JyperionListener()"); this.document = new Document(); this.throwableMap = new HashMap<Integer, Throwable>(); } /** * @see com.beust.testng.ITestListener#onTestSuccess(com.beust.testng.ITestResult) */ public void onTestSuccess(ITestResult result) { log("onTestSuccess("+result+")"); if (successTable == null) { this.successTable = new PdfPTable(new float[]{.3f, .3f, .1f, .3f}); Paragraph p = new Paragraph("PASSED TESTS", new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLD)); p.setAlignment(Element.ALIGN_CENTER); PdfPCell cell = new PdfPCell(p); cell.setColspan(4); cell.setBackgroundColor(Color.GREEN); this.successTable.addCell(cell); cell = new PdfPCell(new Paragraph("Class")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.successTable.addCell(cell); cell = new PdfPCell(new Paragraph("Method")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.successTable.addCell(cell); cell = new PdfPCell(new Paragraph("Time (ms)")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.successTable.addCell(cell); cell = new PdfPCell(new Paragraph("Exception")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.successTable.addCell(cell); } PdfPCell cell = new PdfPCell(new Paragraph(result.getTestClass().toString())); this.successTable.addCell(cell); cell = new PdfPCell(new Paragraph(result.getMethod().getMethodName().toString())); this.successTable.addCell(cell); cell = new PdfPCell(new Paragraph("" + (result.getEndMillis()-result.getStartMillis()))); this.successTable.addCell(cell); Throwable throwable = result.getThrowable(); if (throwable != null) { this.throwableMap.put(new Integer(throwable.hashCode()), throwable); this.nbExceptions++; Paragraph excep = new Paragraph( new Chunk(throwable.toString(), new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.UNDERLINE)). setLocalGoto("" + throwable.hashCode())); cell = new PdfPCell(excep); this.successTable.addCell(cell); } else { this.successTable.addCell(new PdfPCell(new Paragraph(""))); } } /** * @see com.beust.testng.ITestListener#onTestFailure(com.beust.testng.ITestResult) */ public void onTestFailure(ITestResult result) { log("onTestFailure("+result+")"); String file = System.getProperty("user.dir")+"\\Test Results\\Screenshots\\"+"screenshot"+(new Random().nextInt())+".png"; try { Base.takeSnapShot(Base.getDriver(), file); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (this.failTable == null) { this.failTable = new PdfPTable(new float[]{.3f, .3f, .1f, .3f}); this.failTable.setTotalWidth(20f); Paragraph p = new Paragraph("FAILED TESTS", new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLD)); p.setAlignment(Element.ALIGN_CENTER); PdfPCell cell = new PdfPCell(p); cell.setColspan(4); cell.setBackgroundColor(Color.RED); this.failTable.addCell(cell); cell = new PdfPCell(new Paragraph("Class")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.failTable.addCell(cell); cell = new PdfPCell(new Paragraph("Method")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.failTable.addCell(cell); cell = new PdfPCell(new Paragraph("Time (ms)")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.failTable.addCell(cell); cell = new PdfPCell(new Paragraph("Exception")); cell.setBackgroundColor(Color.LIGHT_GRAY); this.failTable.addCell(cell); } PdfPCell cell = new PdfPCell(new Paragraph(result.getTestClass().toString())); this.failTable.addCell(cell); cell = new PdfPCell(new Paragraph(result.getMethod().getMethodName().toString())); this.failTable.addCell(cell); cell = new PdfPCell(new Paragraph("" + (result.getEndMillis()-result.getStartMillis()))); this.failTable.addCell(cell); //String exception = result.getThrowable() == null ? "" : result.getThrowable().toString(); //cell = new PdfPCell(new Paragraph(exception)); //this.failTable.addCell(cell); Throwable throwable = result.getThrowable(); if (throwable != null) { this.throwableMap.put(new Integer(throwable.hashCode()), throwable); this.nbExceptions++; Chunk imdb = new Chunk("[SCREEN SHOT]", new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.UNDERLINE)); imdb.setAction(new PdfAction("file:///"+file)); Paragraph excep = new Paragraph( throwable.toString()); excep.add(imdb); //Paragraph excep = new Paragraph(ck.setLocalGoto("" + throwable.hashCode())); cell = new PdfPCell(excep); this.failTable.addCell(cell); } else { this.failTable.addCell(new PdfPCell(new Paragraph(""))); } } /** * @see com.beust.testng.ITestListener#onTestSkipped(com.beust.testng.ITestResult) */ public void onTestSkipped(ITestResult result) { log("onTestSkipped("+result+")"); } /** * @see com.beust.testng.ITestListener#onStart(com.beust.testng.ITestContext) */ public void onStart(ITestContext context) { log("onStart("+context+")"); try { PdfWriter.getInstance(this.document, new FileOutputStream(System.getProperty("user.dir")+"\\Test Results\\Automation Test Report"+".pdf")); } catch (Exception e) { e.printStackTrace(); } this.document.open(); Paragraph p = new Paragraph(context.getName() + " TESTNG RESULTS", FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD, new Color(0, 0, 255))); try { this.document.add(p); this.document.add(new Paragraph(new Date().toString())); } catch (DocumentException e1) { e1.printStackTrace(); } } /** * @see com.beust.testng.ITestListener#onFinish(com.beust.testng.ITestContext) */ public void onFinish(ITestContext context) { log("onFinish("+context+")"); try { if (this.failTable != null) { log("Added fail table"); this.failTable.setSpacingBefore(15f); this.document.add(this.failTable); this.failTable.setSpacingAfter(15f); } if (this.successTable != null) { log("Added success table"); this.successTable.setSpacingBefore(15f); this.document.add(this.successTable); this.successTable.setSpacingBefore(15f); } } catch (DocumentException e) { e.printStackTrace(); } Paragraph p = new Paragraph("EXCEPTIONS SUMMARY", FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0))); try { this.document.add(p); } catch (DocumentException e1) { e1.printStackTrace(); } Set<Integer> keys = this.throwableMap.keySet(); assert keys.size() == this.nbExceptions; for(Integer key : keys) { Throwable throwable = this.throwableMap.get(key); Chunk chunk = new Chunk(throwable.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(255, 0, 0))); chunk.setLocalDestination("" + key); Paragraph throwTitlePara = new Paragraph(chunk); try { this.document.add(throwTitlePara); } catch (DocumentException e3) { e3.printStackTrace(); } StackTraceElement[] elems = throwable.getStackTrace(); String exception = ""; for(StackTraceElement ste : elems) { Paragraph throwParagraph = new Paragraph(ste.toString()); try { this.document.add(throwParagraph); } catch (DocumentException e2) { e2.printStackTrace(); } } } this.document.close(); } /** * log * @param o */ public static void log(Object o) { //System.out.println("[JyperionListener] " + o); } public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) { // TODO Auto-generated method stub } public void onTestStart(ITestResult arg0) { // TODO Auto-generated method stub } }
2. Use JyperionListener.java in TestNG class, find below code of TestNG class:
import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import reporting.JyperionListener; import reusable.Base; @Listeners(JyperionListener.class) public class google { static Logger log = Logger.getLogger(NewTest.class); static Logger elog = Logger.getLogger("errorLog"); WebDriver driver; @Test public void google1() { PropertyConfigurator.configure("src/main/resources/utilities/log4j.properties"); log.info("Starting first test case"); driver = Base.getDriver(); driver.get("http://www.google.com/"); Assert.assertTrue(false); elog.error("Test Case Fail"); } }
Subscribe to:
Posts (Atom)