Source:Extent Report 3 Add Screenshot
    Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
    Iterable<String> iterable = stream::iterator;
    for (String s : iterable) {
        fileWriter.append(s);
    }
Best Testng code snippet using org.testng.Interface ITestResult
Source:TestListener.java  
1/*******************************************************************************2 * * Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved.3 *  *4 *  * Licensed under the Apache License, Version 2.0 (the "License"); you may not5 *  * use this file except in compliance with the License.  You may obtain a copy6 *  * of the License at7 *  *8 *  *   http://www.apache.org/licenses/LICENSE-2.09 *  *10 *  * Unless required by applicable law or agreed to in writing, software11 *  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12 *  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the13 *  * License for the specific language governing permissions and limitations under14 *  * the License.15 ******************************************************************************/16package com.tmobile.ct.codeless.test.testng.listeners;17import org.testng.ITestContext;18import org.testng.ITestListener;19import org.testng.ITestResult;20import com.tmobile.ct.codeless.core.Test;21import com.tmobile.ct.codeless.test.extentreport.ExtentTestManager;22import org.slf4j.Logger;23import org.slf4j.LoggerFactory;24/**25 * The listener interface for receiving test events.26 * The class that is interested in processing a test27 * event implements this interface, and the object created28 * with that class is registered with a component using the29 * component's <code>addTestListener<code> method. When30 * the test event occurs, that object's appropriate31 * method is invoked.32 *33 * @author Rob Graff34 * @author Sai Chandra Korpu35 * @see TestEvent36 */37public class TestListener implements ITestListener {38	public static final Logger log = LoggerFactory.getLogger(TestListener.class);39	/**40	 * Gets the test method name.41	 *42	 * @param iTestResult the i test result43	 * @return the test method name44	 */45	private static String getTestMethodName(ITestResult iTestResult) {46		return iTestResult.getMethod().getConstructorOrMethod().getName();47	}48	/* (non-Javadoc)49	 * @see org.testng.ITestListener#onTestStart(org.testng.ITestResult)50	 */51	@Override52	public void onTestStart(ITestResult result) {53		log.debug("Entering TestListener.onTestStart method " + getTestMethodName(result) + " start");54		Test test = (Test) result.getParameters()[0];55		ExtentTestManager.startTest(test.getName(), "Test Start");56	}57	/* (non-Javadoc)58	 * @see org.testng.ITestListener#onTestSuccess(org.testng.ITestResult)59	 */60	@Override61	public void onTestSuccess(ITestResult result) {62		log.debug("Entering TestListener.onTestSuccess method " + getTestMethodName(result) + " succeed");63		// Extentreports log operation for passed tests.64		// ExtentTestManager.getTest().log(LogStatus.PASS, "Test passed");65	}66	/* (non-Javadoc)67	 * @see org.testng.ITestListener#onTestFailure(org.testng.ITestResult)68	 */69	@Override70	public void onTestFailure(ITestResult iTestResult) {71		// To add it in the extent report72		// logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));73		/*74		 * log.debug("Entering TestListener.onTestFailure method " +75		 * getTestMethodName(iTestResult) + " failed");76		 * 77		 * // Get driver from BaseTest and assign to local webdriver variable. Object78		 * testClass = iTestResult.getInstance(); WebDriver webDriver = ((WebTest)79		 * testClass).getDriver();80		 * 81		 * // Take base64Screenshot screenshot. String base64Screenshot =82		 * "data:image/png;base64," + ((TakesScreenshot)83		 * webDriver).getScreenshotAs(OutputType.BASE64);84		 * 85		 * // Extentreports log and screenshot operations for failed tests.86		 * ExtentTestManager.getTest().log(LogStatus.FAIL, "Test Failed",87		 * ExtentTestManager.getTest().addBase64ScreenShot(base64Screenshot));88		 */89	}90	/* (non-Javadoc)91	 * @see org.testng.ITestListener#onTestSkipped(org.testng.ITestResult)92	 */93	@Override94	public void onTestSkipped(ITestResult iTestResult) {95		log.debug("Entering TestListener.onTestSkipped method " + getTestMethodName(iTestResult) + " skipped!");96		// Extentreports log operation for skipped tests.97		// ExtentTestManager.getTest().log(LogStatus.SKIP, "Test Skipped");98		log.error("skip exception:: "+iTestResult.getThrowable());99		iTestResult.getThrowable().printStackTrace();100	}101	/* (non-Javadoc)102	 * @see org.testng.ITestListener#onTestFailedButWithinSuccessPercentage(org.testng.ITestResult)103	 */104	@Override105	public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {106		log.debug("Test failed but it is in defined success ratio " + getTestMethodName(iTestResult));107	}108	/* (non-Javadoc)109	 * @see org.testng.ITestListener#onStart(org.testng.ITestContext)110	 */111	@Override112	public void onStart(ITestContext context) {113		log.debug("Entering TestListener.onStart method " + context.getName());114//		context.setAttribute("WebDriver", this.getDriver());115		116	}117	/* (non-Javadoc)118	 * @see org.testng.ITestListener#onFinish(org.testng.ITestContext)119	 */120	@Override121	public void onFinish(ITestContext context) {122		log.debug("Entering TestListener.onFinish method " + context.getName());123		ExtentTestManager.endTest();124		ExtentTestManager.getReporter().flush();125	}126}...Source:Listener.java  
1package com.HFramework.utility;2import org.testng.IInvokedMethod;3import org.testng.IInvokedMethodListener;4import org.testng.ISuite;5import org.testng.ISuiteListener;6import org.testng.ITestContext;7import org.testng.ITestListener;8import org.testng.ITestNGMethod;9import org.testng.ITestResult;10import org.testng.Reporter;11public class Listener implements ITestListener, ISuiteListener, IInvokedMethodListener {12	/*13	 * What is Listeners in Selenium WebDriver? 14	 * Listener is defined as interface that modifes the default TestNG's behavior. As the name suggests Listeners15	 * "listen" to the event defined in the selenium script and behave accordingly.16	 * It is used in selenium by implementing Listeners Interface. It allows17	 * customizing TestNG reports or logs. There are many types of TestNG listeners18	 * available19	 * 20	 * Types of Listeners in TestNG There are many types of listeners which allows21	 * you to change the TestNG's behavior.22	 * 23	 * Below are the few TestNG listeners:24	 * 25	 * IAnnotationTransformer , IAnnotationTransformer2 , IConfigurable ,26	 * IConfigurationListener , IExecutionListener, IHookable ,27	 * IInvokedMethodListener , IInvokedMethodListener2 , IMethodInterceptor ,28	 * IReporter, ISuiteListener, ITestListener . Above Interface are called TestNG29	 * Listeners. These interfaces are used in selenium to generate logs or30	 * customize the Testing reports.31	 */32	// This belongs to ISuiteListener and will execute before the Suite start33	public void onStart(ISuite isuitestart) {34		Reporter.log("About to begin executing Suite " + isuitestart.getName(), true);35	}36	// This belongs to ISuiteListener and will execute, once the Suite is finished37	public void onFinish(ISuite isuiteend) {38		Reporter.log("About to end executing Suite " + isuiteend.getName(), true);39	}40	// This belongs to ITestListener and will execute before starting of Test41	// set/batch42	public void onStart(ITestContext iteststart) {43		Reporter.log("About to begin executing Test " + iteststart.getName(), true);44	}45	// This belongs to ITestListener and will execute, once the Test set/batch is46	// finished47	public void onFinish(ITestContext itestend) {48		Reporter.log("Completed executing test " + itestend.getName(), true);49	}50	// This belongs to ITestListener and will execute only when the test is pass51	public void onTestSuccess(ITestResult itestpass) {52		// This is calling the printTestResults method53		printTestResults(itestpass);54	}55	// This belongs to ITestListener and will execute only on the event of fail test56	public void onTestFailure(ITestResult itestfail) {57		// This is calling the printTestResults method58		printTestResults(itestfail);59	}60	// This belongs to ITestListener and will execute before the main test start61	// (@Test)62	public void onTestStart(ITestResult mainiteststart) {63		System.out.println("The execution of the main test starts now");64	}65	// This belongs to ITestListener and will execute only if any of the main66	// test(@Test) get skipped67	public void onTestSkipped(ITestResult mainitestskiped) {68		printTestResults(mainitestskiped);69	}70	// This is just a piece of shit, ignore this71	public void onTestFailedButWithinSuccessPercentage(ITestResult successpercentage) {72		73		System.out.println(successpercentage);74	}75	// This is the method which will be executed in case of test pass or fail76	// This will provide the information on the test77	private void printTestResults(ITestResult result) {78		Reporter.log("Test Method resides in " + result.getTestClass().getName(), true);79		if (result.getParameters().length != 0) {80			String params = null;81			for (Object parameter : result.getParameters()) {82				params += parameter.toString() + ",";83			}84			Reporter.log("Test Method had the following parameters : " + params, true);85		}86		String status = null;87		switch (result.getStatus()) {88		case ITestResult.SUCCESS:89			status = "Pass";90			break;91		case ITestResult.FAILURE:92			status = "Failed";93			break;94		case ITestResult.SKIP:95			status = "Skipped";96		}97		Reporter.log("Test Status: " + status, true);98	}99	// This belongs to IInvokedMethodListener and will execute before every method100	// including @Before @After @Test101	public void beforeInvocation(IInvokedMethod methodname, ITestResult itestresults) {102		String textMsg = "About to begin executing following method : " + returnMethodName(methodname.getTestMethod());103		Reporter.log(textMsg, true);104	}105	// This belongs to IInvokedMethodListener and will execute after every method106	// including @Before @After @Test107	public void afterInvocation(IInvokedMethod arg1, ITestResult arg2) {108		String textMsg = "Completed executing following method : " + returnMethodName(arg1.getTestMethod());109		Reporter.log(textMsg, true);110	}111	// This will return method names to the calling function112	private String returnMethodName(ITestNGMethod method) {113		return method.getRealClass().getSimpleName() + "." + method.getMethodName();114	}115}...Source:TestListenerFailPass.java  
1package 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/*19 * It's very easy to generate your own reports with TestNG with Listeners and Reporters:20Listeners implement the interface org.testng.ITestListener and are notified in real time 21of when a test starts, passes, fails, etc...22Reporters implement the interface org.testng.IReporter and are notified when all the suites 23have been run by TestNG. The IReporter instance receives a list of objects24 that describe the entire test run.25 */26/*27 * I chose to extend TestListenerAdapter, which implements ITestListener with empty methods, 28 * so I don't have to override other methods from the interface that I have no interest in. 29 * If you try public class 'TestScreenshotOnFailure implements ITestResult' - implementing an interface  instead of 30 * extending your class with a TestNG class that implements the interface you want (ITestResult) then31 * you will have to override ALL (15-18) methods declared in ITestResult interface which is not productive32 */33/*THIS CLASS DEFINES RULES for DEFAULT BEHAVIOUR of  org.testng.ITestResult.Failure or Success34 * http://testng.org/javadocs/constant-values.html#org.testng.ITestResult.FAILURE35 * TO USE THIS CLASS:36 * 37 *put this annotation before you class where you define your test methods38 * @Listeners({ com.quicksilver.util.TestListenerFailPass.class })39 */40public class TestListenerFailPass extends TestListenerAdapter {41	42	WebDriver driver;43	private int m_count = 0;44	Logger log=WebDriverManager.LoggerGetInstance();45	46	ReadingProperties rp = new ReadingProperties();47	String failPath=rp.readConfigProperties("fail.screenshot.path");48	String passPath=rp.readConfigProperties("pass.screenshot.path");49	String usergenPath =rp.readConfigProperties("usergen.screenshot.path");50	51	@Override52	public void onTestFailure(ITestResult tr) {53		//log("Failed");//testng logger54		driver   = WebDriverManager.getDriverInstance();55		WebDriverManager.getBrowser(driver);56		File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);57		DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");58		String destDir = System.getProperty("user.dir")+failPath;59		new File(destDir).mkdirs();60		String destFile = dateFormat.format(new Date()) + ".png";61		try {62			FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));63		} catch (IOException e) {64			e.printStackTrace();65			System.out.println("Could not take screenshot on failure"+ tr.getInstanceName());//getInstanceName =package+className66			log.debug("Could not take screenshot on failure"+ tr.getInstanceName());//getInstanceName =package+className67		}68		Reporter.setEscapeHtml(false);69		Reporter.log("Saved <a href=../screenshot/FAIL/" + destFile + ">Screenshot</a>");70	}71	@Override72	public void onTestSkipped(ITestResult tr) {73		log("Skipped test");74		Reporter.log("Skipped test to avoid test failure due to dependency");75	}76	@Override77	public void onTestSuccess(ITestResult tr) {78		//log("Pass");79	driver = WebDriverManager.getDriverInstance();80		File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);81		DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");82		String destDir = System.getProperty("user.dir")+passPath;83		new File(destDir).mkdirs();84		String destFile = dateFormat.format(new Date()) + ".png";85		try {86			FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));87		} catch (IOException e) {88			e.printStackTrace();89			System.out.println("Could not take screenshot on success"+ tr.getInstanceName());//getInstanceName =package+className90			log.debug("Could not take screenshot on success"+ tr.getInstanceName());//getInstanceName =package+className91		}92		Reporter.setEscapeHtml(false);93		Reporter.log("Saved <a href=../screenshot/PASS/" + destFile + ">Screenshot</a>");94	}95	private void log(String string) {96		System.out.print(string);97		if (++m_count % 40 == 0) {98			System.out.println("");99		}100	}101	102	103	public void onFinish(ISuite suite)104	/*every time testng finished running a testsuite it should create a folder  - label it with suite name and date of run105	 * 106	 */107	{108		109	}110}...Source:ReportListener.java  
1package com.core.api.config;23import org.testng.ITestContext;4import org.testng.ITestListener;5import org.testng.ITestResult;6import org.testng.annotations.Test;78// TODO: Auto-generated Javadoc9/**10 * The listener interface for receiving report events. The class that is11 * interested in processing a report event implements this interface, and the12 * object created with that class is registered with a component using the13 * component's addReportListener method. When the report event14 * occurs, that object's appropriate method is invoked.15 * 16 * @author Pavan.DV17 * @since 1.318 */19public class ReportListener implements ITestListener {2021	/**22	 * Gets the test name.23	 *24	 * @param result the result25	 * @return the test name26	 */27	public String getTestName(ITestResult result) {28		Test testAnnotation = result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);29		if (testAnnotation != null && !"".equals(testAnnotation.testName().trim())) {30			return testAnnotation.testName().trim();31		}32		return result.getTestName() != null ? result.getTestName()33				: result.getMethod().getConstructorOrMethod().getName();34	}3536	/**37	 * Gets the main test name.38	 *39	 * @param result the result ,if not available return the Test class name40	 * @return the main test name41	 */42	public String getMainTestName(ITestResult result) {43		result.getMethod().isDataDriven();44		Test test = result.getTestClass().getRealClass().getDeclaredAnnotation(Test.class);45		if (test != null && !"".equalsIgnoreCase(test.testName().trim())) {46			return test.testName().trim();47		}48		return result.getTestClass().getRealClass().getSimpleName();49	}5051	/**52	 * Gets the main test name.53	 *54	 * @param result the result ,if not available return the Test class name55	 * @return the main test name56	 */57	public String getMainTestDescription(ITestResult result) {58		Test test = result.getTestClass().getRealClass().getDeclaredAnnotation(Test.class);59		if (test != null && !"".equalsIgnoreCase(test.description().trim())) {60			return test.description().trim();61		}62		return "";63	}6465	/**66	 * Gets the main test name.67	 *68	 * @param result the result ,if not available return the Test class name69	 * @return the main test name70	 */71	public String[] getTestGroups(ITestResult result) {72		return result.getMethod().getGroups();73	}7475	/**76	 * Gets the test description.77	 *78	 * @param result the result79	 * @return the test description80	 */81	public String getTestDescription(ITestResult result) {82		return result.getMethod().getDescription() != null ? result.getMethod().getDescription() : getTestName(result);83	}8485	/* (non-Javadoc)86	 * @see org.testng.ITestListener#onTestStart(org.testng.ITestResult)87	 */88	@Override89	public void onTestStart(ITestResult result) {90		ExtentReportManager.startTest(getMainTestName(result), getMainTestDescription(result), getTestName(result),91				getTestDescription(result), getTestGroups(result));92	}9394	/* (non-Javadoc)95	 * @see org.testng.ITestListener#onTestSuccess(org.testng.ITestResult)96	 */97	@Override98	public void onTestSuccess(ITestResult result) {99		100	}101102	/* (non-Javadoc)103	 * @see org.testng.ITestListener#onTestFailure(org.testng.ITestResult)104	 */105	@Override106	public void onTestFailure(ITestResult result) {107		Throwable t = result.getThrowable();108		@SuppressWarnings("unused")109		String cause = "";110		if (t != null)111			cause = t.getMessage();112		try {113			ReportUtil.logException(t);114		} catch (Exception e) {115			e.printStackTrace();116		}117	}118119	/* (non-Javadoc)120	 * @see org.testng.ITestListener#onTestSkipped(org.testng.ITestResult)121	 */122	@Override123	public void onTestSkipped(ITestResult result) {124	}125126	/* (non-Javadoc)127	 * @see org.testng.ITestListener#onTestFailedButWithinSuccessPercentage(org.testng.ITestResult)128	 */129	@Override130	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {131	}132133	/* (non-Javadoc)134	 * @see org.testng.ITestListener#onStart(org.testng.ITestContext)135	 */136	@Override137	public void onStart(ITestContext context) {138	}139140	/* (non-Javadoc)141	 * @see org.testng.ITestListener#onFinish(org.testng.ITestContext)142	 */143	@Override144	public void onFinish(ITestContext context) {145		ExtentReportManager.getExtentReports().flush();146	}147148}
...Source:TestngListener.java  
1package main.java.com.dbyl.appiumCore.testng;2import java.lang.reflect.Method;3import java.util.List;4import org.testng.ITestContext;5import org.testng.ITestNGMethod;6import org.testng.ITestResult;7import org.testng.TestListenerAdapter;8import main.java.com.dbyl.appiumCore.utils.CaseId;9/**10 * The listener interface for receiving testng events. The class that is11 * interested in processing a testng event implements this interface, and the12 * object created with that class is registered with a component using the13 * component's <code>addTestngListener<code> method. When the testng event14 * occurs, that object's appropriate method is invoked.15 *16 * @author Young17 * @version V1.018 * @see TestngEvent19 */20public class TestngListener extends TestListenerAdapter {21	/*22	 * (non-Javadoc)23	 * 24	 * @see org.testng.TestListenerAdapter#onTestFailure(org.testng.ITestResult)25	 */26	@Override27	public void onTestFailure(ITestResult tr) {28		ITestNGMethod im = tr.getMethod();29		getCaseID(im);30		super.onTestFailure(tr);31	}32	/*33	 * (non-Javadoc)34	 * 35	 * @see org.testng.TestListenerAdapter#onTestSkipped(org.testng.ITestResult)36	 */37	@Override38	public void onTestSkipped(ITestResult tr) {39		ITestNGMethod im = tr.getMethod();40		getCaseID(im);41		super.onTestSkipped(tr);42	}43	/*44	 * (non-Javadoc)45	 * 46	 * @see org.testng.TestListenerAdapter#onStart(org.testng.ITestContext)47	 */48	@Override49	public void onStart(ITestContext testContext) {50		System.out.println("Start Test");51		super.onStart(testContext);52	}53	/*54	 * (non-Javadoc)55	 * 56	 * @see org.testng.TestListenerAdapter#onFinish(org.testng.ITestContext)57	 */58	@Override59	public void onFinish(ITestContext testContext) {60		// TODO Auto-generated method stub61		super.onFinish(testContext);62	}63	/*64	 * (non-Javadoc)65	 * 66	 * @see org.testng.TestListenerAdapter#getFailedTests()67	 */68	@Override69	public List<ITestResult> getFailedTests() {70		// TODO Auto-generated method stub71		return super.getFailedTests();72	}73	/*74	 * (non-Javadoc)75	 * 76	 * @see org.testng.TestListenerAdapter#getPassedTests()77	 */78	@Override79	public List<ITestResult> getPassedTests() {80		// TODO Auto-generated method stub81		return super.getPassedTests();82	}83	/*84	 * (non-Javadoc)85	 * 86	 * @see org.testng.TestListenerAdapter#getSkippedTests()87	 */88	@Override89	public List<ITestResult> getSkippedTests() {90		// TODO Auto-generated method stub91		return super.getSkippedTests();92	}93	/*94	 * (non-Javadoc)95	 * 96	 * @see org.testng.TestListenerAdapter#onTestStart(org.testng.ITestResult)97	 */98	@Override99	public void onTestStart(ITestResult result) {100		ITestNGMethod im = result.getMethod();101		getCaseID(im);102		super.onTestStart(result);103	}104	/**105	 * Gets the case ID.106	 *107	 * @param im108	 *            the im109	 * @return the case ID110	 */111	private String[] getCaseID(ITestNGMethod im) {112		Method m = im.getConstructorOrMethod().getMethod();113		CaseId caseId = m.getAnnotation(CaseId.class);114		if (null != caseId) {115			for (String str : caseId.id()) {116				System.out.println("++++++++++++++++>>>>>>>>>>>>>\n\n\n" + str + "<<<<<<<\n\n");117			}118			return caseId.id();119		}120		return null;121	}122	/*123	 * (non-Javadoc)124	 * 125	 * @see org.testng.TestListenerAdapter#getTestContexts()126	 */127	@Override128	public List<ITestContext> getTestContexts() {129		// TODO Auto-generated method stub130		return super.getTestContexts();131	}132}...Source:TestNameListener.java  
1package com.akkadu.reporting;23import java.lang.reflect.Field;45import org.testng.ITestResult;6import org.testng.Reporter;7import org.testng.TestListenerAdapter;8import org.testng.internal.BaseTestMethod;9import org.testng.internal.TestResult;1011/**12 * The listener interface for receiving testName events. The class that is13 * interested in processing a testName event implements this interface, and the14 * object created with that class is registered with a component using the15 * component's <code>addTestNameListener<code> method. When the testName event16 * occurs, that object's appropriate method is invoked.17 *18 * @author Chandan Kumar19 */20public class TestNameListener extends TestListenerAdapter {2122	/**23	 * Sets the test name in xml.24	 *25	 * @param tr the new test name in xml26	 */27	private void setTestNameInXml(ITestResult tr) {28		try {29			Field mMethod = TestResult.class.getDeclaredField("m_method");30			mMethod.setAccessible(true);31			mMethod.set(tr, tr.getMethod().clone());32			Field mMethodName = BaseTestMethod.class.getDeclaredField("m_methodName");33			mMethodName.setAccessible(true);34			mMethodName.set(tr.getMethod(), tr.getTestName());35		} catch (IllegalAccessException ex) {36			Reporter.log(ex.getLocalizedMessage(), true);37		} catch (NoSuchFieldException ex) {38			ex.getMessage();39		}40	}4142	/*43	 * (non-Javadoc)44	 *45	 * @see org.testng.TestListenerAdapter#onTestSuccess(org.testng.ITestResult)46	 */47	@Override48	public void onTestSuccess(ITestResult tr) {49		setTestNameInXml(tr);50		super.onTestSuccess(tr);51	}5253	/*54	 * (non-Javadoc)55	 *56	 * @see org.testng.TestListenerAdapter#onTestFailure(org.testng.ITestResult)57	 */58	@Override59	public void onTestFailure(ITestResult tr) {60		setTestNameInXml(tr);61		super.onTestFailure(tr);62	}6364	/*65	 * (non-Javadoc)66	 *67	 * @see org.testng.TestListenerAdapter#onTestSkipped(org.testng.ITestResult)68	 */69	@Override70	public void onTestSkipped(ITestResult tr) {71		setTestNameInXml(tr);72		super.onTestSkipped(tr);73	}74
...Source:TestNGConfigurationListener.java  
1/*2 * Copyright 2011 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *      http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.gradle.api.internal.tasks.testing.testng;17import org.testng.ITestResult;18/**19 * Our version of TestNG's IConfigurationListener. Can be adapted to20 * org.testng.internal.IConfigurationListener (from TestNG < 6.2) or21 * org.testng.IConfigurationListener2 (from TestNG >= 6.2). Became22 * necessary because TestNG 6.2 changed the package name of the former23 * interface from org.testng.internal to org.testng.24 * 25 * @see TestNGListenerAdapterFactory26 */27public interface TestNGConfigurationListener {28    /**29     * Invoked whenever a configuration method succeeded.30     */31    void onConfigurationSuccess(ITestResult itr);32    /**33     * Invoked whenever a configuration method failed.34     */35    void onConfigurationFailure(ITestResult itr);36    /**37     * Invoked whenever a configuration method was skipped.38     */39    void onConfigurationSkip(ITestResult itr);40    /**41     * Invoked before a configuration method is invoked. 42     * 43     * Note: This method is only invoked for TestNG 6.2 or higher.44     */45    void beforeConfiguration(ITestResult tr);46}...Source:ITestResultNotifier.java  
1package org.testng.internal;2import java.util.List;3import java.util.Set;4import org.testng.IConfigurationListener;5import org.testng.ITestListener;6import org.testng.ITestNGMethod;7import org.testng.ITestResult;8import org.testng.xml.XmlTest;9/**10 * An interface defining the notification for @Test results and also11 * \@Configuration results.12 *13 * @author <a href="mailto:cedric@beust.com">Cedric Beust</a>14 * @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>15 */16public interface ITestResultNotifier {17  Set<ITestResult> getPassedTests(ITestNGMethod tm);18  Set<ITestResult> getFailedTests(ITestNGMethod tm);19  Set<ITestResult> getSkippedTests(ITestNGMethod tm);20  void addPassedTest(ITestNGMethod tm, ITestResult tr);21  void addSkippedTest(ITestNGMethod tm, ITestResult tr);22  void addFailedTest(ITestNGMethod tm, ITestResult tr);23  void addFailedButWithinSuccessPercentageTest(ITestNGMethod tm, ITestResult tr);24  void addInvokedMethod(InvokedMethod im);25  XmlTest getTest();26  List<ITestListener> getTestListeners();27  List<IConfigurationListener> getConfigurationListeners();28}...Interface ITestResult
Using AI Code Generation
1import org.testng.ITestResult;2import org.testng.ITestContext;3import org.testng.ITestListener;4public class TestListener implements ITestListener {5    public void onTestStart(ITestResult result) {6        System.out.println("Test Started: " + result.getName());7    }8    public void onTestSuccess(ITestResult result) {9        System.out.println("Test Passed: " + result.getName());10    }11    public void onTestFailure(ITestResult result) {12        System.out.println("Test Failed: " + result.getName());13    }14    public void onTestSkipped(ITestResult result) {15        System.out.println("Test Skipped: " + result.getName());16    }17    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {18        System.out.println("Test Failed but within success percentage: " + result.getName());19    }20    public void onStart(ITestContext context) {21        System.out.println("Test Started: " + context.getName());22    }23    public void onFinish(ITestContext context) {24        System.out.println("Test Finished: " + context.getName());25    }26}Interface ITestResult
Using AI Code Generation
1import org.testng.ITestResult;2import org.testng.ITestContext;3import org.testng.ITestListener;4import org.testng.Reporter;5public class TestListener implements ITestListener {6    public void onTestStart(ITestResult result) {7        Reporter.log("Test started: " + result.getName());8    }9    public void onTestSuccess(ITestResult result) {10        Reporter.log("Test success: " + result.getName());11    }12    public void onTestFailure(ITestResult result) {13        Reporter.log("Test failed: " + result.getName());14    }15    public void onTestSkipped(ITestResult result) {16        Reporter.log("Test skipped: " + result.getName());17    }18    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {19        Reporter.log("Test failed with success percentage: " + result.getName());20    }21    public void onStart(ITestContext context) {22        Reporter.log("Test started: " + context.getName());23    }24    public void onFinish(ITestContext context) {25        Reporter.log("Test finished: " + context.getName());26    }27}28import org.testng.annotations.Listeners;29import org.testng.annotations.Test;30@Listeners(TestListener.class)31public class TestWithListener {32    public void test1() {33        System.out.println("Test 1");34    }35    public void test2() {36        System.out.println("Test 2");37    }38}Interface ITestResult
Using AI Code Generation
1import org.testng.ITestResult;2import org.testng.annotations.AfterMethod;3import org.testng.annotations.Test;4public class TestNGTestResult {5    public void testMethod1() {6        System.out.println("Running -> testMethod1");7    }8    public void testMethod2() {9        System.out.println("Running -> testMethod2");10    }11    public void afterMethod(ITestResult result) {12        System.out.println("Method finished: " + result.getName());13    }14}Interface ITestResult
Using AI Code Generation
1package com.test;2import org.testng.ITestResult;3import org.testng.TestListenerAdapter;4public class TestListener extends TestListenerAdapter {5public void onStart(ITestContext tr) {6Reporter.log("About to begin executing Test " + tr.getName(), true);7}8public void onFinish(ITestContext tr) {9Reporter.log("Completed executing test " + tr.getName(), true);10}11public void onTestSuccess(ITestResult tr) {12Reporter.log("Test passed", true);13}14public void onTestFailure(ITestResult tr) {15Reporter.log("Test Failed", true);16}17public void onTestStart(ITestResult tr) {18Reporter.log("Test started running", true);19}20public void onTestSkipped(ITestResult tr) {21Reporter.log("Test Skipped", true);22}23}Interface ITestResult
Using AI Code Generation
1import org.testng.ITestResult;2import java.util.Date;3import java.text.SimpleDateFormat;4import java.util.Calendar;5import java.util.GregorianCalendar;6import java.util.concurrent.TimeUnit;7import java.util.regex.Matcher;8import java.util.regex.Pattern;9import java.util.regex.PatternSyntaxException;10import java.io.*;11import org.apache.commons.io.FileUtils;12import org.apache.commons.io.FilenameUtils;13import org.apache.commons.io.IOUtils;14import org.apache.commons.io.LineIterator;15import org.apache.commons.io.output.*;16import org.apache.commons.io.input.*;17import org.apache.commons.io.filefilter.*;18import org.apache.commons.io.filefilter.FileFilterUtils;19import org.apache.commons.io.filefilter.IOFileFilter;20import org.apache.commons.io.filefilter.TrueFileFilter;21import org.apache.commons.io.filefilter.WildcardFileFilter;22import org.apache.commons.io.filefilter.SuffixFileFilter;23import org.apache.commons.io.filefilter.PrefixFileFilter;24import org.apache.commons.io.filefilter.NameFileFilter;25import org.apache.commons.io.filefilter.DirectoryFileFilter;26import org.apache.commons.io.filefilter.AgeFileFilter;27import org.apache.commons.io.filefilter.AndFileFilter;28import org.apache.commons.io.filefilter.NotFileFilter;29import org.apache.commons.io.filefilter.OrFileFilter;30import org.apache.commons.io.filefilter.HiddenFileFilter;31import org.apache.commons.io.filefilter.CanReadFileFilter;32import org.apache.commons.io.filefilter.CanWriteFileFilter;33import org.apache.commons.io.filefilter.CanExecuteFileFilter;34import org.apache.commons.io.filefilter.EmptyFileFilter;35import org.apache.commons.io.filefilter.FileFileFilter;36import org.apache.commons.io.filefilter.SizeFileFilter;37import org.apache.commons.io.filefilter.RegexFileFilter;38import org.apache.commons.io.filefilter.TrueFileFilter;39import org.apache.commons.io.filefilter.FalseFileFilter;40import org.apache.commons.io.filefilter.FileFilterUtils;41import org.apache.commons.io.filefilter.WildcardFilter;42import org.apache.commons.io.filefilter.SuffixFilter;43import org.apache.commons.io.filefilter.PrefixFilter;44import org.apache.commons.io.filefilter.NameFileFilter;45import org.apache.commons.io.filefilter.DirectoryFileFilter;46import org.apache.commons.io.filefilter.AgeFileFilter;47import org.apache.commons.io.filefilter.AndFileFilter;48import org.apache.commons.io.filefilter.NotFileFilter;49import org.apache.commons.io.filefilter.OrFileFilter;50import org.apache.commons.io.filefilter.HiddenFileFilter;51import org.apache.commons.io.filefilter.CanReadFileFilter;Interface ITestResult
Using AI Code Generation
1import org.testng.ITestResult;2import org.testng.TestListenerAdapter;3public class TestNGListener extends TestListenerAdapter {4    public void onTestSuccess(ITestResult tr) {5        System.out.println("Test method success: " + tr.getName());6    }7    public void onTestFailure(ITestResult tr) {8        System.out.println("Test method failed: " + tr.getName());9    }10    public void onTestSkipped(ITestResult tr) {11        System.out.println("Test method skipped: " + tr.getName());12    }13}14import org.testng.annotations.Test;15@Listeners({ TestNGListener.class })16public class MyTest {17    public void testMethod1() {18        System.out.println("TestNG Listener -> testMethod1");19    }20    public void testMethod2() {21        System.out.println("TestNG Listener -> testMethod2");22    }23}24import org.testng.annotations.Test;25@Listeners({ TestNGListener.class })26public class MyTest2 {27    public void testMethod3() {28        System.out.println("TestNG Listener -> testMethod3");29    }30    public void testMethod4() {31        System.out.println("TestNG Listener -> testMethod4");32    }33}34import org.testng.annotations.Test;35@Listeners({ TestNGListener.class })36public class MyTest3 {37    public void testMethod5() {38        System.out.println("TestNG Listener -> testMethod5");39    }40    public void testMethod6() {41        System.out.println("TestNG Listener -> testMethod6");42    }43}44import org.testng.annotations.Test;45@Listeners({ TestNGListener.class })46public class MyTest4 {47    public void testMethod7() {48        System.out.println("TestNG Listener -> testMethod7");49    }50    public void testMethod8() {51        System.out.println("TestNG Listener -> testMethod8");Source: Extent Report 3 Add Screenshot 
1    Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());2    Iterable<String> iterable = stream::iterator;3    for (String s : iterable) {4        fileWriter.append(s);5    }6TestNG 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!!
