Source:How to convert TestNG report index.html to pdf
if(somethingIsTrue()) {
  String message = "Everything is fine";
} else {
  String message = "We have an error";
}
System.out.println(message);
Best Testng code snippet using org.testng.Interface IReporter
Source:SendEmail.java  
12package yahoo.toolbar.webDriver.util;34import java.io.File;5import java.security.Timestamp;6import java.sql.Date;7import java.text.DateFormat;8import java.text.SimpleDateFormat;9import java.util.List;10import java.util.Map;11import java.util.Properties;12import java.util.TimeZone;13import java.text.SimpleDateFormat;14import java.io.File; 1516import javax.mail.Message;17import javax.mail.MessagingException;18import javax.mail.Session;19import javax.mail.Transport;20import javax.mail.internet.InternetAddress;21import javax.mail.internet.MimeMessage;2223import org.testng.IReporter;24import org.testng.ISuite;25import org.testng.ISuiteResult;26import org.testng.ITestContext;27import org.testng.annotations.AfterSuite;28import org.testng.xml.XmlSuite;29import org.testng.xml.XmlTest;303132/**33 * Class used to send email after test suite execution , implements IReporter interface34 * @author asingla35 **/3637public class SendEmail extends CommonLibrary implements IReporter 38{39	/**40	 * 41	 * Variable decalaration's section42	 * 43	 * declare object and class variables in this section44	 **/45	46	String outputDirectory;47	private int passedTestCases;48	private int failedTestCases=0;49	private int skippedTestCases=0;50	//variable to check email is send only once51	static int cond=0;52	53	54	/**55	 * Method's declaration section56	 * 57	 * define all of the methods in this section58	 * 59	 **/60	61	62	63	64	/**65	 * Method to generate report after test execution is complete , it override generateReport method of IReporter66	 * 67	 * @xmlSuites=xml suites list that testng used68	 * @suites= list of suites testng used69	 * @outputDirectory=directory to which output report will be generated70	 **/71	72	@Override73	public void generateReport(java.util.List<XmlSuite> xmlSuites, java.util.List<ISuite> suites,String outputDirectory) 74	{75		//get testng tests and fetch result of suite execution76		XmlSuite suite=xmlSuites.get(0);77		List<XmlTest> xmlTests=suite.getTests();78		Map<String,ISuiteResult> result=suites.get(0).getResults();79		80		//loop through all the tests to find passed , skipped, failed testcases81		for(int i=0;i<xmlTests.size();i++)82		{83			//get the ITestContext and the result of test84			ITestContext testContext=result.get(xmlTests.get(i).getName()).getTestContext();85			passedTestCases+=testContext.getPassedTests().size();86			failedTestCases+=testContext.getFailedTests().size();87			skippedTestCases+=testContext.getSkippedTests().size();88			89		}90		91		//check if sendMail is true in XPathList.xml, if true send mail92		if(getPath("Config","SendEmail","sendMail").equals("true"))93		{94			//at present testng sending email twice after suite run, so adding check to ensure email is sent only once95			if(cond==0)96			{	97				sendEmail();98				cond++;99			}100		}101	}102	103	 104	105	/**106	 * 107	 *Method to send email108	 */109	private void sendEmail()110	{111		//define @to,@from,@host,@totalTestCases112		int totalTestCases=passedTestCases+failedTestCases+skippedTestCases;113		String to = "toolbar-eng@yahoo-inc.com";114		String from = "GalaxyAutomation@yahoo-inc.com";115	    Properties properties = System.getProperties();116	    properties.setProperty("mail.smtp.host", "smtp.yahoo.com");117	    //use default session118	    Session session = Session.getDefaultInstance(properties);119	    120	  121122	    123	   124		 125	   try126	   {127	        //Create a default MimeMessage object.128	        MimeMessage message = new MimeMessage(session);129	        //Set From: header field130	        message.setFrom(new InternetAddress(from));131	        //Set To: header field132	        message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));133	        //Set Subject: header field134	        message.setSubject("Galaxy Automation report");135	        //actual message136	        message.setContent(137	       		"<html></body>" +138	       		"Hi All,<br/>" +139	       		"<br>Please find below the automation run report:</br><br/>" +140	        	"<br>" +141	       		"<TABLE width='100%' border='1'>" +142	       		"<tr>" +143	       		"<th>Total Test Executed</th>" +144	       		"<th>Test Passed</th>" +145	       		"<th>Test Failed</th>" +146        		"<th>Test Skipped</th>" +147	       		"</tr>" +148	        	"<tr>" +149	        	"<td align='center'>"+totalTestCases+"</td>" +150	        	"<td align='center'>"+passedTestCases+"</td>" +151	        	"<td align='center'>"+failedTestCases+"</td>" +152	        	"<td align='center'>"+skippedTestCases+"</td>" +153	        	"</tr>" +154	        	"</TABLE>" +155	        	"</br>" +156	        	"<br>" +157	        	"Please find the detailed report <a href='http://aq-tools2.ysm.corp.sp2.yahoo.com//toolbarautomation//Galaxy//emailable-report.html'>Click</a></br><br/>" +158	        	"<br>Thanks</br>" +159	        	"<br>Sandesh</br>" +160	    		"</html></body>" ,"text/html");161	        162	         // Send message163	         Transport.send(message);164	         System.out.println("Sent message successfully....");165	         166	         /**167	    	 *168	    	 * config method to Move the report after test suite run 169	    	 * 170	    	 **/171	    	172	    	173	    	    	174	    	    	try{175	    	    		176	    	    		177	    	    		 File file = new File("C:\\xampp\\htdocs\\toolbarautomation\\Galaxy\\");        178	    	    	        String[] myFiles;      179	    	    	            if(file.isDirectory()){  180	    	    	                myFiles = file.list();  181	    	    	                for (int i=0; i<myFiles.length; i++) {  182	    	    	                    File myFile = new File(file, myFiles[i]);   183	    	    	                    myFile.delete();  184	    	    	                }  185	    	    	             }  186	    	 187	    	    	   File afile =new File("C:\\Nano\\galaxy\\target\\surefire-reports\\emailable-report.html");188	    	    	  // java.util.Date date= new java.util.Date();189	    	    		// System.out.println(new Timestamp(date.getTime()));190	    	    	   191	    	    	   if(afile.renameTo(new File("C:\\xampp\\htdocs\\toolbarautomation\\Galaxy\\" + afile.getName()))){192	    	    		System.out.println("File is moved successful!");193	    	    	   }else{194	    	    		System.out.println("File is failed to move!");195	    	    	   }196	    	 197	    	    	}catch(Exception e){198	    	    		e.printStackTrace();199	    	    	}200	    	    }201	    202		catch (MessagingException mex) 203		{204			mex.printStackTrace();205		}206	}207}
...Source:SendEmail_New.java  
1package yahoo.toolbar.webDriver.util;23import java.util.*;4import javax.mail.*;5import javax.mail.internet.*;6import javax.activation.*;78import javax.activation.DataSource;9import javax.activation.FileDataSource;10import javax.mail.Message;11import javax.mail.MessagingException;12import javax.mail.PasswordAuthentication;13import javax.mail.Session;14import javax.mail.Transport;15import javax.mail.internet.InternetAddress;16import javax.mail.internet.MimeMessage;1718import org.testng.IReporter;19import org.testng.ISuite;20import org.testng.ISuiteResult;21import org.testng.ITestContext;22import org.testng.annotations.AfterSuite;23import org.testng.xml.XmlSuite;24import org.testng.xml.XmlTest;2526import java.util.Properties;27 28import javax.mail.Message;29import javax.mail.MessagingException;30import javax.mail.PasswordAuthentication;31import javax.mail.Session;32import javax.mail.Transport;33import javax.mail.internet.InternetAddress;34import javax.mail.internet.MimeMessage;353637/**38 * Class used to send email after test suite execution , implements IReporter interface39 * @author asingla40 **/4142public class SendEmail_New extends CommonLibrary implements IReporter 43{44	private static final String String = null;45	/**46	 * 47	 * Variable decalaration's section48	 * 49	 * declare object and class variables in this section50	 **/51	52	String outputDirectory;53	private int passedTestCases;54	private int failedTestCases=0;55	private int skippedTestCases=0;56	//variable to check email is send only once57	static int cond=0;58	59	60	/**61	 * Method's declaration section62	 * 63	 * define all of the methods in this section64	 * 65	 **/66	67	68	69	70	/**71	 * Method to generate report after test execution is complete , it override generateReport method of IReporter72	 * 73	 * @xmlSuites=xml suites list that testng used74	 * @suites= list of suites testng used75	 * @outputDirectory=directory to which output report will be generated76	 **/77	78	@Override79	public void generateReport(java.util.List<XmlSuite> xmlSuites, java.util.List<ISuite> suites,String outputDirectory) 80	{81		//get testng tests and fetch result of suite execution82		XmlSuite suite=xmlSuites.get(0);83		List<XmlTest> xmlTests=suite.getTests();84		Map<String,ISuiteResult> result=suites.get(0).getResults();85		86		//loop through all the tests to find passed , skipped, failed testcases87		for(int i=0;i<xmlTests.size();i++)88		{89			//get the ITestContext and the result of test90			ITestContext testContext=result.get(xmlTests.get(i).getName()).getTestContext();91			passedTestCases+=testContext.getPassedTests().size();92			failedTestCases+=testContext.getFailedTests().size();93			skippedTestCases+=testContext.getSkippedTests().size();94			95		}96		97		//check if sendMail is true in XPathList.xml, if true send mail98		if(getPath("Config","SendEmail","sendMail").equals("true"))99		{100			//at present testng sending email twice after suite run, so adding check to ensure email is sent only once101			if(cond==0)102			{	103				sendEmail();104				cond++;105			}106		}107	}108	109110@AfterSuite(alwaysRun=true)111private void sendEmail()112{113114	int totalTestCases=passedTestCases+failedTestCases+skippedTestCases;115	String to = "hsandesh@yahoo-inc.com";116	String from = "GalaxyReports@yahoo-inc.com";117    Properties properties = System.getProperties();118    properties.setProperty("mail.smtp.host", "smtp.yahoo.com");119    //use default session120    Session session = Session.getDefaultInstance(properties);121	122  //2) compose message   123  try{124    MimeMessage message = new MimeMessage(session);125    message.setFrom(new InternetAddress(from));126    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));127    message.setSubject("Galaxy Apps Automation Report");128    129    //3) create MimeBodyPart object and set your message content    130    BodyPart messageBodyPart1 = new MimeBodyPart();131  messageBodyPart1.setText("This is message body");132  messageBodyPart1.setContent(133       		"<html></body>" +134       		"Hi All,<br/>" +135       		"<br>Please find below the automation run report:</br><br/>" +136        	"<br>" +137     		"<TABLE width='100%' border='1'>" +138       		"<tr>" +139       		"<th>Total Test Executed</th>" +140       		"<th>Test Passed</th>" +141       		"<th>Test Failed</th>" +142    		"<th>Test Skipped</th>" +143       		"</tr>" +144        	"<tr>" +145        	"<td align='center'>"+totalTestCases+"</td>" +146        	"<td align='center'>"+passedTestCases+"</td>" +147       	"<td align='center'>"+failedTestCases+"</td>" +148        	"<td align='center'>"+skippedTestCases+"</td>" +149        	"</tr>" +150        	"</TABLE>" +151        	"</br>" +152       	"<br>" +153        	"Please find the Attahed report.</br><br/>" +154        	"<br>Thanks</br>" +155       	"<br>Sandesh</br>" +156    		"</html></body>" ,"text/html");157    158    //4) create new MimeBodyPart object and set DataHandler object to this object    159    MimeBodyPart messageBodyPart2 = new MimeBodyPart();160161    String filename = "C:\\Nano\\galaxy\\target\\surefire-reports\\emailable-report.html";//change accordingly162    DataSource source = new FileDataSource(filename);163    messageBodyPart2.setDataHandler(new DataHandler(source));164    messageBodyPart2.setFileName(filename);165   166   167    //5) create Multipart object and add MimeBodyPart objects to this object    168    Multipart multipart = new MimeMultipart();169    multipart.addBodyPart(messageBodyPart1);170    multipart.addBodyPart(messageBodyPart2);171172    //6) set the multiplart object to the message object173    message.setContent(multipart );174   175    //7) send message176    Transport.send(message);177 178   System.out.println("message sent....");179   }catch (MessagingException ex) {ex.printStackTrace();}180 }181}
...Source:TestListenerFailPass.java  
1/*package com.quiksilver.util;2import java.io.File;3import java.io.IOException;4import java.text.DateFormat;5import java.text.SimpleDateFormat;6import java.util.Date;7import org.apache.commons.io.FileUtils;8import org.openqa.selenium.OutputType;9import org.openqa.selenium.TakesScreenshot;10import org.openqa.selenium.WebDriver;11import org.testng.ISuite;12import org.testng.ITestResult;13import org.testng.Reporter;14import org.testng.TestListenerAdapter;15import org.testng.annotations.AfterMethod;16import org.testng.annotations.Listeners;17import org.apache.log4j.*;18 * It's very easy to generate your own reports with TestNG with Listeners and Reporters:19Listeners implement the interface org.testng.ITestListener and are notified in real time 20of when a test starts, passes, fails, etc...21Reporters implement the interface org.testng.IReporter and are notified when all the suites 22have been run by TestNG. The IReporter instance receives a list of objects23 that describe the entire test run.24 25 * I chose to extend TestListenerAdapter, which implements ITestListener with empty methods, 26 * so I don't have to override other methods from the interface that I have no interest in. 27 * If you try public class 'TestScreenshotOnFailure implements ITestResult' - implementing an interface  instead of 28 * extending your class with a TestNG class that implements the interface you want (ITestResult) then29 * you will have to override ALL (15-18) methods declared in ITestResult interface which is not productive30 31THIS CLASS DEFINES RULES for DEFAULT BEHAVIOUR of  org.testng.ITestResult.Failure or Success32 * http://testng.org/javadocs/constant-values.html#org.testng.ITestResult.FAILURE33 * TO USE THIS CLASS:34 * 35 *put this annotation before you class where you define your test methods36 * @Listeners({ com.quicksilver.util.TestListenerFailPass.class })37 38public class TestListenerFailPass extends TestListenerAdapter {39	40	WebDriver driver;41	private int m_count = 0;42	Logger log=WebDriverManager.LoggerGetInstance();43	44	ReadingProperties rp = new ReadingProperties();45	String failPath=rp.readConfigProperties("fail.screenshot.path");46	String passPath=rp.readConfigProperties("pass.screenshot.path");47	String usergenPath =rp.readConfigProperties("usergen.screenshot.path");48	49	@Override50	public void onTestFailure(ITestResult tr) {51		//log("Failed");//testng logger52		driver   = WebDriverManager.getDriverInstance();53		WebDriverManager.getBrowser(driver);54		File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);55		DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");56		String destDir = System.getProperty("user.dir")+failPath;57		new File(destDir).mkdirs();58		String destFile = dateFormat.format(new Date()) + ".png";59		try {60			FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));61		} catch (IOException e) {62			e.printStackTrace();63			System.out.println("Could not take screenshot on failure"+ tr.getInstance());//getInstanceName =package+className64			log.debug("Could not take screenshot on failure"+ tr.getInstance());//getInstanceName =package+className65		}66		//Reporter.setEscapeHtml(false);67		Reporter.log("Saved <a href=../screenshot/FAIL/" + destFile + ">Screenshot</a>");68	}69	@Override70	public void onTestSkipped(ITestResult tr) {71		log("Skipped test");72		Reporter.log("Skipped test to avoid test failure due to dependency");73	}74	@Override75	public void onTestSuccess(ITestResult tr) {76		//log("Pass");77	driver = WebDriverManager.getDriverInstance();78		File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);79		DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");80		String destDir = System.getProperty("user.dir")+passPath;81		new File(destDir).mkdirs();82		String destFile = dateFormat.format(new Date()) + ".png";83		try {84			FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));85		} catch (IOException e) {86			e.printStackTrace();87			System.out.println("Could not take screenshot on success"+ tr.getInstance());//getInstanceName =package+className88			log.debug("Could not take screenshot on success"+ tr.getInstance());//getInstanceName =package+className89		}90		//Reporter.setEscapeHtml(false);91		Reporter.log("Saved <a href=../screenshot/PASS/" + destFile + ">Screenshot</a>");92	}93	private void log(String string) {94		System.out.print(string);95		if (++m_count % 40 == 0) {96			System.out.println("");97		}98	}99	100	101	public void onFinish(ISuite suite)102	every time testng finished running a testsuite it should create a folder  - label it with suite name and date of run103	 * 104	 105	{106		107	}108}109*/...Source:Constants.java  
1package test.listeners.ordering;2public interface Constants {3  String IALTERSUITELISTENER_ALTER = "org.testng.IAlterSuiteListener.alter(List<XmlSuite> suites)";4  String IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS = "org.testng.IAnnotationTransformer.transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod)";5  String METHODINTERCEPTOR_INTERCEPT = "org.testng.IMethodInterceptor.intercept(List<IMethodInstance> methods, ITestContext context)";6  String IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION = "org.testng.IExecutionVisualiser.consumeDotDefinition(String dotDefinition)";7  String IREPORTER_GENERATE_REPORT = "org.testng.IReporter.generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory)";8  String ISUITELISTENER_ON_START = "org.testng.ISuiteListener.onStart()";9  String ISUITELISTENER_ON_FINISH = "org.testng.ISuiteListener.onFinish()";10  String ITESTLISTENER_ON_START_TEST_METHOD = "org.testng.ITestListener.onTestStart(ITestResult result)";11  String ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD = "org.testng.ITestListener.onTestFailure(ITestResult result)";12  String ITESTLISTENER_ON_TEST_TIMEOUT_TEST_METHOD = "org.testng.ITestListener.onTestFailedWithTimeout(ITestResult result)";13  String ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD = "org.testng.ITestListener.onTestSuccess(ITestResult result)";14  String ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD = "org.testng.ITestListener.onTestSkipped(ITestResult result)";15  String ITESTLISTENER_ON_START_TEST_TAG = "org.testng.ITestListener.onStart(ITestContext context)";16  String ITESTLISTENER_ON_FINISH_TEST_TAG = "org.testng.ITestListener.onFinish(ITestContext context)";17  String ICLASSLISTENER_ON_BEFORE_CLASS = "org.testng.IClassListener.onBeforeClass(ITestClass testClass)";18  String ICLASSLISTENER_ON_AFTER_CLASS = "org.testng.IClassListener.onAfterClass(ITestClass testClass)";19  String IINVOKEDMETHODLISTENER_BEFORE_INVOCATION = "org.testng.IInvokedMethodListener.beforeInvocation(IInvokedMethod method, ITestResult testResult)";20  String IINVOKEDMETHODLISTENER_AFTER_INVOCATION = "org.testng.IInvokedMethodListener.afterInvocation(IInvokedMethod method, ITestResult testResult)";21  String IEXECUTIONLISTENER_ON_EXECUTION_START = "org.testng.IExecutionListener.onExecutionStart()";22  String IEXECUTIONLISTENER_ON_EXECUTION_FINISH = "org.testng.IExecutionListener.onExecutionFinish()";23  String IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION = "org.testng.IDataProviderListener.beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext)";24  String IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION = "org.testng.IDataProviderListener.afterDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext)";25  String ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION = "org.testng.IConfigurationListener.beforeConfiguration(ITestResult tr)";26  String ICONFIGURATIONLISTENER_ON_CONFIGURATION_SUCCESS = "org.testng.IConfigurationListener.onConfigurationSuccess(ITestResult itr)";27  String ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE = "org.testng.IConfigurationListener.onConfigurationFailure(ITestResult itr)";28  String ICONFIGURATIONLISTENER_ON_CONFIGURATION_SKIP = "org.testng.IConfigurationListener.onConfigurationSkip(ITestResult itr)";29}...Source:ExtentReporterListener.java  
1/*2 * @autor : Naveen Khunteta3 * 4 */5package com.qa.ExtentReportListener;6import java.io.File;7import java.util.Calendar;8import java.util.Date;9import java.util.List;10import java.util.Map;11import org.testng.IReporter;12import org.testng.IResultMap;13import org.testng.ISuite;14import org.testng.ISuiteResult;15import org.testng.ITestContext;16import org.testng.ITestResult;17import org.testng.xml.XmlSuite;18import com.relevantcodes.extentreports.ExtentReports;19import com.relevantcodes.extentreports.ExtentTest;20import com.relevantcodes.extentreports.LogStatus;21/*1.ExtentReaporterNG fully/completely dependend on TestNG ! 222.This class implements the IReporter interface which is inside the TestNG. testNG listener is necessary 233.Need to add one listener to the runner.xml //testng.xml file to "generate the report"244.Refresh the project after running then see the output folder for extent.html folder , copy the path 25and paste on the browser to see th report26-->video #527*/28public class ExtentReporterListener implements IReporter {29	private ExtentReports extent;30	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {31		extent = new ExtentReports(outputDirectory + File.separator + "Extent.html", true);32		//"Extent.html" ==can be the project name like "amazon_Extent.html==folder /file--> output report dir"33		for (ISuite suite : suites) {34			Map<String, ISuiteResult> result = suite.getResults();35			for (ISuiteResult r : result.values()) {36				ITestContext context = r.getTestContext();37				buildTestNodes(context.getPassedTests(), LogStatus.PASS);38				buildTestNodes(context.getFailedTests(), LogStatus.FAIL);39				buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);40			}41		}42		extent.flush();43		extent.close();44	}45	private void buildTestNodes(IResultMap tests, LogStatus status) {46		ExtentTest test;47		if (tests.size() > 0) {48			for (ITestResult result : tests.getAllResults()) {49				test = extent.startTest(result.getMethod().getMethodName());50				test.setStartedTime(getTime(result.getStartMillis()));51				test.setEndedTime(getTime(result.getEndMillis()));52				for (String group : result.getMethod().getGroups())53					test.assignCategory(group);54				if (result.getThrowable() != null) {55					test.log(status, result.getThrowable());56				} else {57					test.log(status, "Test " + status.toString().toLowerCase() + "ed");58				}59				extent.endTest(test);60			}61		}62	}63	private Date getTime(long millis) {64		Calendar calendar = Calendar.getInstance();65		calendar.setTimeInMillis(millis);66		return calendar.getTime();67	}68}...Source:ExtentReporterNG.java  
1package ExtentReportListeners;2import java.io.File;3import java.util.Calendar;4import java.util.Date;5import java.util.List;6import java.util.Map;7import org.testng.IReporter;8import org.testng.IResultMap;9import org.testng.ISuite;10import org.testng.ISuiteResult;11import org.testng.ITestContext;12import org.testng.ITestResult;13import org.testng.xml.XmlSuite;14import com.relevantcodes.extentreports.ExtentReports;15import com.relevantcodes.extentreports.ExtentTest;16import com.relevantcodes.extentreports.LogStatus;17public class ExtentReporterNG implements IReporter {18	private ExtentReports extent;19	20	21	/*22	 * generateReport - This is abstract method of IReporter interface23	 * 24	 */25	26	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,27			String outputDirectory) {28		extent = new ExtentReports(outputDirectory + File.separator29				+ "ExtentReport.html", true);30		for (ISuite suite : suites) {31			Map<String, ISuiteResult> result = suite.getResults();32			for (ISuiteResult r : result.values()) {33				ITestContext context = r.getTestContext();34				buildTestNodes(context.getPassedTests(), LogStatus.PASS);35				buildTestNodes(context.getFailedTests(), LogStatus.FAIL);36				buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);37			}38		}39		extent.flush();40		extent.close();41	}42	private void buildTestNodes(IResultMap tests, LogStatus status) {43		ExtentTest test;44		if (tests.size() > 0) {45			for (ITestResult result : tests.getAllResults()) {46				test = extent.startTest(result.getMethod().getMethodName());47				test.setStartedTime(getTime(result.getStartMillis()));48				test.setEndedTime(getTime(result.getEndMillis()));49				for (String group : result.getMethod().getGroups())50					test.assignCategory(group);51				if (result.getThrowable() != null) {52					test.log(status, result.getThrowable());53				} else {54					test.log(status, "Test " + status.toString().toLowerCase()55							+ "ed");56				}57				extent.endTest(test);58			}59		}60	}61	private Date getTime(long millis) {62		Calendar calendar = Calendar.getInstance();63		calendar.setTimeInMillis(millis);64		return calendar.getTime();65	}66}...Source:IReporter.java  
1package org.testng;2import org.testng.reporters.IReporterConfig;3import org.testng.reporters.PojoReporterConfig;4import org.testng.xml.XmlSuite;5import java.util.List;6/**7 * This interface can be implemented by clients to generate a report. Its method generateReport()8 * will be invoked after all the suite have run and the parameters give all the test results that9 * happened during that run.10 */11public interface IReporter extends ITestNGListener {12  /**13   * Generate a report for the given suites into the specified output directory.14   *15   * @param xmlSuites The list of <code>XmlSuite</code>16   * @param suites The list of <code>ISuite</code>17   * @param outputDirectory The output directory18   */19  default void generateReport(20      List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {21    // not implemented22  }23  /**24   * Get the reporter configuration object.25   * <p>26   * <b>NOTE</b>: Reporter configuration objects must adhere to the JavaBean object conventions,27   * providing getter and setter methods that conform to standard naming rules. This enables28   * {@link org.testng.internal.ReporterConfig} to serialize, deserialize, and instantiate the reporter.29   *30   * @return reporter configuration object31   */32  default IReporterConfig getConfig() {33    return new PojoReporterConfig(this);34  }35}...Source:MyTestNGListeners.java  
1package listeners;2import org.testng.IAnnotationTransformer;3import org.testng.IExecutionListener;4import org.testng.IHookable;5import org.testng.IInvokedMethodListener;6import org.testng.IMethodInterceptor;7import org.testng.IReporter;8import org.testng.ISuiteListener;9import org.testng.ITestListener;10public interface MyTestNGListeners extends IAnnotationTransformer, 11											IHookable, 12											IExecutionListener, 13											IInvokedMethodListener,14											IMethodInterceptor,15											IReporter,16											ISuiteListener,17											ITestListener18{19}...Interface IReporter
Using AI Code Generation
1public class TestNGListner implements IReporter {2	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {3		for (ISuite suite : suites) {4			Map<String, ISuiteResult> suiteResults = suite.getResults();5			for (ISuiteResult sr : suiteResults.values()) {6				ITestContext tc = sr.getTestContext();7				System.out.println("Passed tests for suite '" + suite.getName() + "' is:" + tc.getPassedTests().getAllResults().size());8				System.out.println("Failed tests for suite '" + suite.getName() + "' is:" + tc.getFailedTests().getAllResults().size());9				System.out.println("Skipped tests for suite '" + suite.getName() + "' is:" + tc.getSkippedTests().getAllResults().size());10			}11		}12	}13}Interface IReporter
Using AI Code Generation
1package testng;2import org.testng.IReporter;3import org.testng.ISuite;4import org.testng.xml.XmlSuite;5import java.util.List;6public class CustomReport implements IReporter {7    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {8        System.out.println("Custom report is generated");9    }10}Interface IReporter
Using AI Code Generation
1package com.app.tests;2import org.testng.IReporter;3import org.testng.ISuite;4import org.testng.xml.XmlSuite;5import java.util.List;6import java.util.Map;7public class CustomReporter implements IReporter {8    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {9        for (ISuite suite : suites) {10            String suiteName = suite.getName();11            Map<String, ISuiteResult> suiteResults = suite.getResults();12            for (ISuiteResult sr : suiteResults.values()) {13                ITestContext tc = sr.getTestContext();14                System.out.println("Passed tests for suite '" + suiteName +15                        "' is:" + tc.getPassedTests().getAllResults().size());16                System.out.println("Failed tests for suite '" + suiteName +17                        "' is:" + tc.getFailedTests().getAllResults().size());18                System.out.println("Skipped tests for suite '" + suiteName +19                        "' is:" + tc.getSkippedTests().getAllResults().size());20            }21        }22    }23}24package com.app.tests;25import org.testng.ITestContext;26import org.testng.ITestListener;27import org.testng.ITestResult;28public class CustomListener implements ITestListener {29    public void onFinish(ITestContext arg0) {30        System.out.println("Test finished: " + arg0.getName());31    }32    public void onStart(ITestContext arg0) {33        System.out.println("Test started: " + arg0.getName());34    }35    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {36    }37    public void onTestFailure(ITestResult arg0) {38        System.out.println("Test failed: " + arg0.getName());39    }40    public void onTestSkipped(ITestResult arg0) {41        System.out.println("Test skipped: " + arg0.getName());42    }43    public void onTestStart(ITestResult arg0) {44        System.out.println("Test started: " + arg0.getName());45    }Interface IReporter
Using AI Code Generation
1public class TestNGReport implements IReporter {2    private static final Logger LOGGER = LoggerFactory.getLogger(TestNGReport.class);3    private static final String OUTPUT_FOLDER = "test-output/";4    private static final String FILE_NAME = "index.html";5    private static final String TEMPLATE_FILE = "testng-report-template.ftl";6    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {7        try {8            List<Suite> suitesList = new ArrayList<>();9            for (ISuite suite : suites) {10                suitesList.add(new Suite(suite));11            }12            Configuration configuration = new Configuration();13            configuration.setClassForTemplateLoading(TestNGReport.class, "/");14            configuration.setDefaultEncoding("UTF-8");15            Template template = configuration.getTemplate(TEMPLATE_FILE);16            Map<String, Object> data = new HashMap<>();17            data.put("suites", suitesList);18            File reportFile = new File(OUTPUT_FOLDER + FILE_NAME);19            if (!reportFile.exists()) {20                reportFile.createNewFile();21            }22            Writer file = new FileWriter(reportFile);23            template.process(data, file);24            file.flush();25            file.close();26        } catch (Exception e) {27            LOGGER.error("Error generating TestNG report", e);28        }29    }30}31public class TestNGListener implements ITestListener {32    private static final Logger LOGGER = LoggerFactory.getLogger(TestNGListener.class);33    private static final String OUTPUT_FOLDER = "test-output/";34    private static final String FILE_NAME = "testng-report.json";35    private static final String TEMPLATE_FILE = "testng-report-template.ftl";36    public void onTestStart(ITestResult result) {37        LOGGER.info("Test started: " + result.getName());38    }39    public void onTestSuccess(ITestResult result) {40        LOGGER.info("Test succeeded: " + result.getName());41    }42    public void onTestFailure(ITestResult result) {43        LOGGER.info("Test failed: " + result.getName());44    }45    public void onTestSkipped(ITestResult result) {46        LOGGER.info("Test skipped: " + result.getName());47    }48    public void onTestFailedButWithinSuccessPercentage(ITestResult result)Interface IReporter
Using AI Code Generation
1public class TestNGCustomReporter implements IReporter {2    private static final Logger LOGGER = Logger.getLogger(TestNGCustomReporter.class.getName());3    private static final String OUTPUT_FOLDER = "test-output";4    private static final String FILE_NAME = "CustomReport.html";5    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {6        try {7            File reportDir = new File(OUTPUT_FOLDER);8            if (!reportDir.exists()) {9                reportDir.mkdir();10            }11            BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FOLDER + File.separator + FILE_NAME));12            writer.write("<html><head><title>Custom TestNG Report</title></head><body>");13            writer.write("<h1>Custom TestNG Report</h1>");14            writer.write("<table border='1'>");15            writer.write("<tr><th>Test</th><th>Class</th><th>Method</th><th>Time (ms)</th><th>Status</th></tr>");16            for (ISuite suite : suites) {17                Map<String, ISuiteResult> result = suite.getResults();18                for (ISuiteResult r : result.values()) {19                    ITestContext context = r.getTestContext();20                    for (ITestResult testResult : context.getPassedTests().getAllResults()) {21                        writer.write("<tr><td>" + context.getName() + "</td>");22                        writer.write("<td>" + testResult.getTestClass().getName() + "</td>");23                        writer.write("<td>" + testResult.getMethod().getMethodName() + "</td>");24                        writer.write("<td>" + testResult.getEndMillis() - testResult.getStartMillis() + "</td>");25                        writer.write("<td>Passed</td></tr>");26                    }27                    for (ITestResult testResult : context.getFailedTests().getAllResults()) {28                        writer.write("<tr><td>" + context.getName() + "</td>");29                        writer.write("<td>" + testResult.getTestClass().getName() + "</td>");30                        writer.write("<td>" + testResult.getMethod().getMethodName() + "</td>");31                        writer.write("<td>" + testResult1if(somethingIsTrue()) {2  String message = "Everything is fine";3} else {4  String message = "We have an error";5}6System.out.println(message);7TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.
You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.
Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
