Best Testng code snippet using org.testng.Interface ISuite
Source:Listener.java  
1package selenium_interview_questions;23import org.testng.IInvokedMethod;45import org.testng.IInvokedMethodListener;67import org.testng.ISuite;89import org.testng.ISuiteListener;1011import org.testng.ITestContext;1213import org.testng.ITestListener;1415import org.testng.ITestNGMethod;1617import org.testng.ITestResult;1819import org.testng.Reporter;2021public abstract class Listener implements ITestListener, ISuiteListener, IInvokedMethodListener {2223	/*24	 * What is Listeners in Selenium WebDriver? 25	 * Listener is defined as interface that modifes the default TestNG's behavior. As the name suggests Listeners26	 * "listen" to the event defined in the selenium script and behave accordingly.27	 * 28	 * It is used in selenium by implementing Listeners Interface.29	 * It allows customizing TestNG reports or logs. There are many types of TestNG listeners30	 * available31	 * 32	 * Types of Listeners in TestNG There are many types of listeners which allows33	 * you to change the TestNG's behavior.34	 * 35	 * Below are the few TestNG listeners:36	 * 37	 * IAnnotationTransformer , IAnnotationTransformer2 , IConfigurable ,38	 * IConfigurationListener , IExecutionListener, IHookable ,39	 * IInvokedMethodListener , IInvokedMethodListener2 , IMethodInterceptor ,40	 * IReporter, ISuiteListener, ITestListener41	 * 42	 *  Above Interface are called TestNG Listeners. These interfaces are used in selenium to generate logs or43	 * customize the Testing reports.44	 */4546	// This belongs to ISuiteListener and will execute before the Suite start4748	public void onStart(ISuite arg0) {4950		Reporter.log("About to begin executing Suite " + arg0.getName(), true);5152	}5354	// This belongs to ISuiteListener and will execute, once the Suite is finished5556	public void onFinish(ISuite arg0) {5758		Reporter.log("About to end executing Suite " + arg0.getName(), true);5960	}6162	// This belongs to ITestListener and will execute before starting of Test63	// set/batch6465	public void onStart(ITestContext arg0) {6667		Reporter.log("About to begin executing Test " + arg0.getName(), true);6869	}7071	// This belongs to ITestListener and will execute, once the Test set/batch is72	// finished7374	public void onFinish(ITestContext arg0) {7576		Reporter.log("Completed executing test " + arg0.getName(), true);7778	}7980	// This belongs to ITestListener and will execute only when the test is pass8182	public void onTestSuccess(ITestResult arg0) {8384		// This is calling the printTestResults method8586		printTestResults(arg0);8788	}8990	// This belongs to ITestListener and will execute only on the event of fail test9192	public void onTestFailure(ITestResult arg0) {9394		// This is calling the printTestResults method9596		printTestResults(arg0);9798	}99100	// This belongs to ITestListener and will execute before the main test start101	// (@Test)102103	public void onTestStart(ITestResult arg0) {104105		System.out.println("The execution of the main test starts now");106107	}108109	// This belongs to ITestListener and will execute only if any of the main110	// test(@Test) get skipped111112	public void onTestSkipped(ITestResult arg0) {113114		printTestResults(arg0);115116	}117118	// This is just a piece of shit, ignore this119120	public void onTestFailed_But_Within_Success_Percentage(ITestResult arg0) {121122	}123124	// This is the method which will be executed in case of test pass or fail125126	// This will provide the information on the test127128	private void printTestResults(ITestResult result) {129130		Reporter.log("Test Method resides in " + result.getTestClass().getName(), true);131132		if (result.getParameters().length != 0) {133134			String params = null;135136			for (Object parameter : result.getParameters()) {137138				params += parameter.toString() + ",";139140			}141142			Reporter.log("Test Method had the following parameters : " + params, true);143144		}145146		String status = null;147148		switch (result.getStatus()) {149150		case ITestResult.SUCCESS:151152			status = "Pass";153154			break;155156		case ITestResult.FAILURE:157158			status = "Failed";159160			break;161162		case ITestResult.SKIP:163164			status = "Skipped";165166		}167168		Reporter.log("Test Status: " + status, true);169170	}171172	// This belongs to IInvokedMethodListener and will execute before every method173	// including @Before @After @Test174175	public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) {176177		String textMsg = "About to begin executing following method : " + returnMethodName(arg0.getTestMethod());178179		Reporter.log(textMsg, true);180181	}182183	// This belongs to IInvokedMethodListener and will execute after every method184	// including @Before @After @Test185186	public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) {187188		String textMsg = "Completed executing following method : " + returnMethodName(arg0.getTestMethod());189190		Reporter.log(textMsg, true);191192	}193194	// This will return method names to the calling function195196	private String returnMethodName(ITestNGMethod method) {197198		return method.getRealClass().getSimpleName() + "." + method.getMethodName();199200	}201202}
...Source:SuiteFixtureListener.java  
1package org.opengeospatial.cite.wmts10.ets.core;2import static org.opengeospatial.cite.wmts10.ets.core.util.ServiceMetadataUtils.parseLayerInfo;3import java.io.File;4import java.net.URI;5import java.util.Map;6import java.util.logging.Level;7import org.opengeospatial.cite.wmts10.ets.core.domain.SuiteAttribute;8import org.opengeospatial.cite.wmts10.ets.core.domain.WMTS_Constants;9import org.testng.ISuite;10import org.testng.ISuiteListener;11import org.testng.Reporter;12import org.w3c.dom.Document;13import de.latlon.ets.core.util.TestSuiteLogger;14import de.latlon.ets.core.util.URIUtils;15//import org.opengeospatial.cite.wmts10.ets.core.domain.InteractiveTestResult;16/**17 * A listener that performs various tasks before and after a test suite is run, usually concerned with maintaining a18 * shared test suite fixture. Since this listener is loaded using the ServiceLoader mechanism, its methods will be19 * called before those of other suite listeners listed in the test suite definition and before any annotated20 * configuration methods.21 * 22 * Attributes set on an ISuite instance are not inherited by constituent test group contexts (ITestContext). However,23 * suite attributes are still accessible from lower contexts.24 * 25 * @see org.testng.ISuite ISuite interface26 */27public class SuiteFixtureListener implements ISuiteListener {28    @Override29    public void onStart( ISuite suite ) {30        processWmtsParameter( suite );31        Reporter.clear(); // clear output from previous test runs32        StringBuilder str = new StringBuilder( "Initial test run parameters:\n" );33        str.append( suite.getXmlSuite().getAllParameters().toString() );34        Reporter.log( str.toString() );35        TestSuiteLogger.log( Level.CONFIG, str.toString() );36    }37    @Override38    public void onFinish( ISuite suite ) {39        Reporter.log( "Success? " + !suite.getSuiteState().isFailed() );40        String reportDir = suite.getOutputDirectory();41        String msg = String.format( "Test run directory: %s",42                                    reportDir.substring( 0, reportDir.lastIndexOf( File.separatorChar ) ) );43        Reporter.log( msg );44    }45    /**46     * Processes the "wmts" test suite parameter that specifies a URI reference for the service description47     * (capabilities document). The URI is dereferenced and the entity is parsed; the resulting Document object is set48     * as the value of the {@link SuiteAttribute#TEST_SUBJECT testSubject} suite attribute.49     * 50     * @param suite51     *            An ISuite object representing a TestNG test suite.52     */53    void processWmtsParameter( ISuite suite ) {54        Map<String, String> params = suite.getXmlSuite().getParameters();55        String wmtsRef = params.get( TestRunArg.WMTS.toString() );56        if ( ( null == wmtsRef ) || wmtsRef.isEmpty() ) {57            throw new IllegalArgumentException( "Required parameter not found" );58        }59        URI wmtsURI = URI.create( wmtsRef );60        Document doc = null;61        try {62            doc = URIUtils.resolveURIAsDocument( wmtsURI );63            if ( !WMTS_Constants.WMTS_CAPABILITIES.equals( doc.getDocumentElement().getLocalName() ) ) {64                throw new RuntimeException( "Did not receive WMTS ServeiceMetadata capabilities document: "65                                            + doc.getDocumentElement().getNodeName() );66            }67        } catch ( Exception ex ) {68            // push exception up through TestNG ISuiteListener interface69            throw new RuntimeException( "Failed to parse resource located at " + wmtsURI, ex );70        }71        if ( null != doc ) {72            suite.setAttribute( SuiteAttribute.TEST_SUBJECT.getName(), doc );73            suite.setAttribute( SuiteAttribute.LAYER_INFO.getName(), parseLayerInfo( doc ) );74        }75    }76}...Source:Guru99Reporter.java  
1package com.test.iReporterInterfaceExample;2import java.util.Collection;3import java.util.Date;4import java.util.List;5import java.util.Map;6import java.util.Set;7import org.testng.IReporter;8import org.testng.IResultMap;9import org.testng.ISuite;10import org.testng.ISuiteResult;11import org.testng.ITestContext;12import org.testng.ITestNGMethod;13import org.testng.xml.XmlSuite;14public class Guru99Reporter implements IReporter{15    @Override16    public void generateReport(List<XmlSuite> arg0, List<ISuite> arg1,17            String outputDirectory) {18        // Second parameter of this method ISuite will contain all the suite executed.19        for (ISuite iSuite : arg1) {20         //Get a map of result of a single suite at a time21            Map<String,ISuiteResult> results =    iSuite.getResults();22         //Get the key of the result map23            Set<String> keys = results.keySet();24        //Go to each map value one by one25            for (String key : keys) {26             //The Context object of current result27            ITestContext context = results.get(key).getTestContext();28            //Print Suite detail in Console29             System.out.println("Suite Name->"+context.getName()30                    + "::Report output Ditectory->"+context.getOutputDirectory()31                     +"::Suite Name->"+ context.getSuite().getName()32                     +"::Start Date Time for execution->"+context.getStartDate()33                     +"::End Date Time for execution->"+context.getEndDate());34            35             //Get Map for only failed test cases36            IResultMap resultMap = context.getFailedTests();37            //Get method detail of failed test cases38            Collection<ITestNGMethod> failedMethods = resultMap.getAllMethods();39            //Loop one by one in all failed methods40            System.out.println("--------FAILED TEST CASE---------");41            for (ITestNGMethod iTestNGMethod : failedMethods) {42                //Print failed test cases detail43                System.out.println("TESTCASE NAME->"+iTestNGMethod.getMethodName()44                        +"\nDescription->"+iTestNGMethod.getDescription()45                        +"\nPriority->"+iTestNGMethod.getPriority()46                        +"\n:Date->"+new Date(iTestNGMethod.getDate()));47                48            }49        }50        }51        52    }53}...Source:ExtentReporterNG.java  
1package com.qa.ExtentReportListener;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{ // Ireporter is an interface from testng18	private ExtentReports extent;19	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,20			String outputDirectory) {21		extent = new ExtentReports(outputDirectory + File.separator22				+ "Extent.html", true);23		for (ISuite suite : suites) {24			Map<String, ISuiteResult> result = suite.getResults();25			for (ISuiteResult r : result.values()) {26				ITestContext context = r.getTestContext();27				buildTestNodes(context.getPassedTests(), LogStatus.PASS);28				buildTestNodes(context.getFailedTests(), LogStatus.FAIL);29				buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);30			}31		}32		extent.flush();33		extent.close();34	}35	private void buildTestNodes(IResultMap tests, LogStatus status) {36		ExtentTest test;37		if (tests.size() > 0) {38			for (ITestResult result : tests.getAllResults()) {39				test = extent.startTest(result.getMethod().getMethodName());40				test.setStartedTime(getTime(result.getStartMillis()));41				test.setEndedTime(getTime(result.getEndMillis()));42				for (String group : result.getMethod().getGroups())43					test.assignCategory(group);44				if (result.getThrowable() != null) {45					test.log(status, result.getThrowable());46				} else {47					test.log(status, "Test " + status.toString().toLowerCase()48							+ "ed");49				}50				extent.endTest(test);51			}52		}53	}54	private Date getTime(long millis) {55		Calendar calendar = Calendar.getInstance();56		calendar.setTimeInMillis(millis);57		return calendar.getTime();58	}59}...Source:SuiteListener.java  
1package com.etouch.taf.core.listener;2import java.util.Properties;3import org.apache.commons.logging.Log;4import org.testng.ISuite;5import org.testng.ISuiteListener;6import com.etouch.taf.util.LogUtil;7/**8 * The listener interface for receiving suite events. The class that is9 * interested in processing a suite event implements this interface, and the10 * object created with that class is registered with a component using the11 * component's <code>addSuiteListener<code> method. When the suite event occurs,12 * that object's appropriate method is invoked.13 *14 * @author eTouch Systems Corporation15 */16public class SuiteListener implements ISuiteListener {17	/** The log. */18	static Log log = LogUtil.getLog(SuiteListener.class);19	/** The page ur ls. */20	public static final Properties pageURLs = null;21	/** The rally property file. */22	public static final Properties rallyPropertyFile = null;23	/** The is initialize. */24	static boolean isInitialize = false;25	/*26	 * (non-Javadoc)27	 * 28	 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)29	 */30	@Override31	public void onStart(ISuite arg0) {32		log.info("Suite Name :" + arg0.getName() + " - Start");33	}34	/*35	 * (non-Javadoc)36	 * 37	 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)38	 */39	@Override40	public void onFinish(ISuite arg0) {41		log.info("Suite Name :" + arg0.getName() + " - End");42		log.info("********Results*******");43	}44}...Source:ICustomTestListener.java  
1package com.ui.automation.framework.testng.listener;2import org.testng.ISuite;3import org.testng.ITestContext;4import org.testng.ITestResult;5/**6 * The interface Custom test listener.7 */8public interface ICustomTestListener {9    /**10     * On test failure.11     *12     * @param tr the tr13     */14    void onTestFailure(ITestResult tr);15    /**16     * On test skipped.17     *18     * @param tr the tr19     */20    void onTestSkipped(ITestResult tr);21    /**22     * On test success.23     *24     * @param tr the tr25     */26    void onTestSuccess(ITestResult tr);27    /**28     * On test start.29     *30     * @param tr the tr31     */32    void onTestStart(ITestResult tr);33    /**34     * On start.35     *36     * @param testContext the test context37     */38    void onStart(ITestContext testContext);39    void onStart(ISuite iSuite);40    /**41     * On finish.42     *43     * @param iSuite the test context44     */45    void onFinish(ISuite iSuite);46    void onFinish(ITestContext testContext);47}...Source:IRemoteSuiteListener.java  
1package org.testng.remote.strprotocol;2/**3 * Interface replicating the <code>ISuiteListener</code> used for remote listeners.4 *5 * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>6 * @see org.testng.ISuiteListener7 */8public interface IRemoteSuiteListener {9  /**10   * General information about the number of suites to be run.11   * This is called once before all suites.12   *13   * @param genericMessage a message containing the number of suites that will be run14   */15  void onInitialization(GenericMessage genericMessage);16  /**17   * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)18   *19   * @param suiteMessage the suite message containing the description of the suite to be run.20   */21  void onStart(SuiteMessage suiteMessage);22  /**23   * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)24   *25   * @param suiteMessage the suite message containing infos about the finished suite.26   */27  void onFinish(SuiteMessage suiteMessage);28}...Source:CustomListener3.java  
1package listenerspackage;2import org.testng.ISuite;3import org.testng.ISuiteListener;4import org.testng.ITestContext;5import org.testng.ITestListener;6import org.testng.ITestNGMethod;7import org.testng.ITestResult;8import org.testng.ISuite;9import org.testng.ISuiteListener;10public class CustomListener3 implements ISuiteListener { //interface11	@Override12	public void onStart(ISuite suite) {13		// When <suite> tag starts14		System.out.println("onStart: before suite starts");15	}16	@Override17	public void onFinish(ISuite suite) {18		// When <suite> tag completes19		System.out.println("onFinish: after suite completes");20	}21}...TestNG 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!!
