Best Testng code snippet using org.testng.Interface ISuiteListener
Source:SeleniumGridListener.java
1package com.dd.test.catpaw.platform.grid;2import java.io.File;3import java.util.HashMap;4import org.testng.IInvokedMethod;5import org.testng.IInvokedMethodListener;6import org.testng.ISuite;7import org.testng.ISuiteListener;8import org.testng.ITestContext;9import org.testng.ITestListener;10import org.testng.ITestResult;11import org.testng.Reporter;12import com.dd.test.catpaw.platform.config.CatPawConfig;13import com.dd.test.catpaw.platform.config.ServiceLoaderManager;14import com.dd.test.catpaw.reports.reporter.services.TestCaseUtility;15import com.dd.test.catpaw.reports.runtime.WebReporter;16/**17 * Contains the logic that will take care of all the selenium related18 */19public class SeleniumGridListener implements IInvokedMethodListener, ISuiteListener, ITestListener{20 // used to track browser sessions across all threads21 // data structure format <HashMap<String "sessionName", CatPawWebSession>22 private volatile HashMap<String, CatPawWebSession> sessionMap;23 // private static SimpleLogger logger = CatPawLogger.getLogger();24 25 /**26 * 27 * Identifies which version and name of browser to start if it specified in28 * @webtest <br>29 * <b>sample</b><br>30 * 31 * @webtest(<b>browser="*firefox"</b>)<br>32 * Identifies if test case wants to open new session <br>33 * <b>sample</b><br>34 * @webtest(browser="*firefox", <b>openNewSession = true</b>)35 * 36 * @see org.testng.IInvokedMethodListener#beforeInvocation(org.testng.IInvokedMethod,37 * org.testng.ITestResult)38 */39 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {40 // logger.entering(new Object[] { method, testResult });41 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {42 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);43 return;44 }45 boolean webTest = method.isTestMethod()46 && method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(WebTest.class) != null;47 TestCaseUtility.appendECaseId(method, testResult);48 if (webTest) {49 try {50 // Acquire @WebTest annotation parameter values specified by51 // user52 WebTestConfig webTestConfig = new WebTestConfig().initWebTestConfig(method, sessionMap, testResult);53 String sessionName = webTestConfig.getSessionName();54 // Lazy start the grid on the first encounter of a @WebTest55 // annotated test method56 LocalGridManager.spawnLocalHub(webTestConfig.getBrowser());57 synchronized (this) {58 if (webTestConfig.getOpenNewSession()) {59 // if we already have a session with this name, on this60 // thread, close it61 if (sessionMap.containsKey(sessionName)) {62 IllegalStateException e = new IllegalStateException(63 "Found an existing session ["64 + sessionName65 + "]. Please either change the session name to a unique value or re-use that session.");66 // logger.log(Level.SEVERE, e.getMessage(), e);67 throw e;68 }69 70 CatPawWebSession newSession = Grid.startSession(webTestConfig);71 sessionMap.put(sessionName, newSession);72// if (logger.isLoggable(Level.FINE)) {73// // logger.log(Level.FINE, "Thread " + threadId + " created new " + sessionName + " = "74// + sessionMap.get(sessionName).toString());75// }76 } else {77 // try to switch into a session by the same name78 if (sessionMap.containsKey(sessionName)) {79 CatPawWebSession session = sessionMap.get(sessionName);80 if ((session == null) || (session.getWebDriver() == null)) {81 closeSession(sessionName, true);82 // Tell TestNG the exception occurred in83 // beforeInvocation84 IllegalStateException e = new IllegalStateException("The session " + sessionName85 + " is already closed. It probably timed out.");86 // logger.log(Level.SEVERE, e.getMessage(), e);87 throw e;88 } else {89// if (logger.isLoggable(Level.FINE)) {90// // logger.log(Level.FINE, "Thread " + threadId + " switching into " + sessionName91// + " = " + session.toString());92// }93 Grid.switchSession(sessionMap.get(sessionName), webTestConfig);94 }95 } else {96 IllegalStateException e = new IllegalStateException(97 "Unable to find an already existing session with name [" + sessionName + "].");98 // logger.log(Level.SEVERE, e.getMessage(), e);99 throw e;100 }101 }102 } // synchronized block103 // TODO : We need to be able to segregate CatPaw originated104 // Runtime Exceptions from other runtime105 // exceptions raised by Selenium or JSON. Including a marker for106 // this task here.107 } catch (RuntimeException e) {108 // We are looking for any additional unchecked exceptions that109 // Grid may have thrown110 String errorMsg = "An error occured while setting up the test environment. \nRoot cause: ";111 Reporter.log(errorMsg + e.getMessage(), true);112 // Tell TestNG the exception occurred in beforeInvocation113 RuntimeException runTimeException = new RuntimeException(errorMsg, e);114 testResult.setThrowable(runTimeException);115 // Time to raise an Exception to let TestNG know that the116 // configuration method failed117 // so that it doesn't start executing the test methods.118 // logger.log(Level.SEVERE, e.getMessage(), e);119 throw runTimeException;120 }121 }122 // logger.exiting();123 }124 125 /**126 * Executes when test case is finished<br>127 * 128 * Identify if webtest wants to have session open, otherwise close session<br>129 * <b>sample</b><br>130 * @webtest(browser="*firefox", <b>keepSessionOpen = true</b>)<br>131 * Analyzes failure if any132 * 133 * @see org.testng.IInvokedMethodListener#afterInvocation(org.testng.IInvokedMethod,134 * org.testng.ITestResult)135 * 136 */137 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {138 // logger.entering(new Object[] { method, testResult });139 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {140 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);141 return;142 }143 boolean webTest = method.isTestMethod()144 && method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(WebTest.class) != null;145// TestCaseCalData.setTime(false, method, testResult);146 if (webTest == false) {147 // logger.exiting();148 return;149 }150 // Acquire @WebTest annotation parameter values specified by user151 WebTestConfig webTestConfig = Grid.getWebTestConfig();152 //WebTestConfig would be a Null only under the following conditions (ofcourse because of us throwing an exception)153 //a. If the test-case with same session name already exists.154 //b. If we are unable to find an already existing session with name provided155 //c. Session with the session name is already closed.156 if (webTestConfig == null){157 return;158 }159 if (!webTestConfig.getKeepSessionOpen()) {160 closeSession(webTestConfig.getSessionName(), true);161 }162 // logger.exiting();163 }164 /*165 * go through and close all open sessions166 */167 private synchronized void closeAllSessions() {168 // logger.entering();169 // Close all open sessions170 for (String key : sessionMap.keySet()) {171 closeSession(key, false);172 sessionMap.put(key, null);173 }174 sessionMap.clear();175 // logger.exiting();176 }177 /*178 * close a sessions by name. optionally, also remove it from the sessionMap179 */180 private synchronized void closeSession(String name, boolean removeSessionFromMap) {181 // logger.entering(new Object[] { name, removeSessionFromMap });182 try {183 if ((sessionMap.get(name) != null) && (sessionMap.get(name).getWebDriver() != null)) {184 Grid.closeSession(sessionMap.get(name));185 }186 } catch (Throwable e) {187 // Ignore ... Grid.closeSession seems to ALWAYS throws something.188 } finally {189 sessionMap.put(name, null);190 }191 if (removeSessionFromMap) {192 sessionMap.remove(name);193 }194 // logger.exiting();195 }196 /**197 * Initiate config on suite start198 * 199 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)200 */201 public void onStart(ISuite suite) {202 // Look at public void onStart(ITestContext context) from other Listener203 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {204 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);205 return;206 }207 CatPawConfig.initConfig(suite);208 }209 /**210 * Generates and returns output directory string path211 * 212 * @param base213 * String shows path to the suiteName214 * @param suiteName215 * String suiteName specified by config file216 * @return String - path to output directory for that particular suite217 */218 public static String filterOutputDirectory(String base, String suiteName) {219 // logger.entering(new Object[] { base, suiteName });220 int index = base.lastIndexOf(suiteName);221 String outputFolderWithoutName = base.substring(0, index);222 // logger.exiting(outputFolderWithoutName + File.separator);223 return outputFolderWithoutName + File.separator;224 }225 /**226 * Closes selenium session when suite finished to run227 * 228 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)229 */230 public void onFinish(ISuite suite) {231 // logger.entering(suite);232 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {233 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);234 return;235 }236// if (logger.isLoggable(Level.FINE)) {237// // logger.log(Level.FINE, "Thread " + Thread.currentThread().getId() + " finished Suite, Open Sessions = "238// + sessionMap.toString());239// }240 closeAllSessions();241 LocalGridManager.shutDownHub();242 // logger.exiting();243 }244 /**245 * 246 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)247 */248 public void onFinish(ITestContext context) {249 //Below conditional check needs to be invoked in all TestNG Listener interface implementation.250 //Failing to do so can have un-predictable results.251 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {252 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);253 return;254 }255 return;256 }257 /**258 * On start each suite initialize config object and report object259 */260 public void onStart(ITestContext context) {261 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {262 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);263 return;264 }265 sessionMap = new HashMap<String, CatPawWebSession>();266 ISuite suite = context.getSuite();267 CatPawConfig.initConfig(context);268 String base = suite.getOutputDirectory();269 String suiteName = suite.getName();270 String rootFolder = filterOutputDirectory(base, suiteName);271 WebReporter.setTestNGOutputFolder(rootFolder);272 WebReporter.init();273 }274 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {275 //Below conditional check needs to be invoked in all TestNG Listener interface implementation.276 //Failing to do so can have un-predictable results.277 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {278 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);279 return;280 }281 return;282 }283 public void onTestFailure(ITestResult result) {284 //Below conditional check needs to be invoked in all TestNG Listener interface implementation.285 //Failing to do so can have un-predictable results.286 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {287 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);288 return;289 }290 return;291 }292 public void onTestSkipped(ITestResult result) {293 //Below conditional check needs to be invoked in all TestNG Listener interface implementation.294 //Failing to do so can have un-predictable results.295 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {296 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);297 return;298 }299 return;300 }301 public void onTestStart(ITestResult result) {302 //Below conditional check needs to be invoked in all TestNG Listener interface implementation.303 //Failing to do so can have un-predictable results.304 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {305 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);306 return;307 }308 return;309 }310 public void onTestSuccess(ITestResult result) {311 //Below conditional check needs to be invoked in all TestNG Listener interface implementation.312 //Failing to do so can have un-predictable results.313 if (ServiceLoaderManager.executeCurrentMethod(this) == false) {314 // logger.exiting(ServiceLoaderManager.THREAD_EXCLUSION_MSG);315 return;316 }317 return;318 }319 320}...
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:TestNGListeners.java
1package listeners;2import org.testng.ISuiteListener;3import org.testng.ITestNGListener;4import org.testng.ITestResult;5public class TestNGListeners implements ITestNGListener, ISuiteListener {6 /*/7 https://javadoc.jitpack.io/com/github/cbeust/testng/master/javadoc/org/testng/ITestListener.html8 https://testng.org/doc/documentation-main.html#logging-listeners9 Listeners are interfaces in TestNG library10 How to use TestNG listeners11 Step 112 Create a new package and new Class13 Step 214 Implement ITestListener interface15 public class TestNGListener implements ITestListener16 Step 317 Add unimplemented methods of ITestListener interface18 Step 419 Create a Demo class and provide annotation20 @Listeners(packageName.ClassName)21 Step 522 Run and validate23 How to use at Suite Level (multiple classes)24 Step 125 Create testng.xml file26 Step 227 Define listeners in testng.xml file28 Step 329 Run and validate30 Adding more listeners from TestNG31 You can implement more listener interfaces in your existing class and add implemented methods32 */33 //adding unimplemented methods of the interfaces34 public void onTestStart(ITestResult result){35 System.out.print("**********************Test Started *********************"+result.getName());36 }37 public void onTestFailure(ITestResult result){38 System.out.print("**********************Test Failed *********************"+result.getName());39 }40 public void onTestSkipped(ITestResult result){41 System.out.print("**********************Test Test Skipped *********************"+result.getName());42 }43 public void onTestFailedButWithSuccessPercentage(ITestNGListener result) {44 }45 public void onFinish(ITestResult context) {46 System.out.print("**********************Tests Completed *********************"+context.getName());47 }48}...
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: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 run 14 */15 void onInitialization(GenericMessage genericMessage);16 /**17 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)18 *19 * @param sm 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}...
Interface ISuiteListener
Using AI Code Generation
1public class TestNGListener implements ISuiteListener {2 public void onStart(ISuite arg0) {3 }4 public void onFinish(ISuite arg0) {5 }6}7public class TestNGListener implements ITestListener {8 public void onTestStart(ITestResult arg0) {9 }10 public void onTestSuccess(ITestResult arg0) {11 }12 public void onTestFailure(ITestResult arg0) {13 }14 public void onTestSkipped(ITestResult arg0) {15 }16 public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {17 }18 public void onStart(ITestContext arg0) {19 }20 public void onFinish(ITestContext arg0) {21 }22}23public class TestNGListener implements IInvokedMethodListener {24 public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) {25 }26 public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) {27 }28}29public class TestNGListener implements IAnnotationTransformer {30 public void transform(ITestAnnotation arg0, Class arg1, Constructor arg2, Method arg3) {31 }32}33public class TestNGListener implements IReporter {34 public void generateReport(List arg0, List arg1, String arg2) {35 }36}
Interface ISuiteListener
Using AI Code Generation
1public class TestNGListener implements ISuiteListener {2 public void onStart(ISuite suite) {3 Reporter.log("Suite started: " + suite.getName(), true);4 }5 public void onFinish(ISuite suite) {6 Reporter.log("Suite finished: " + suite.getName(), true);7 }8}9public class TestNGListener implements ITestListener {10 public void onTestStart(ITestResult result) {11 Reporter.log("Test started: " + result.getName(), true);12 }13 public void onTestSuccess(ITestResult result) {14 Reporter.log("Test success: " + result.getName(), true);15 }16 public void onTestFailure(ITestResult result) {17 Reporter.log("Test failed: " + result.getName(), true);18 }19 public void onTestSkipped(ITestResult result) {20 Reporter.log("Test skipped: " + result.getName(), true);21 }22 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {23 Reporter.log("Test failed but within success %: " + result.getName(), true);24 }25 public void onStart(ITestContext context) {26 Reporter.log("Test started: " + context.getName(), true);27 }28 public void onFinish(ITestContext context) {29 Reporter.log("Test finished: " + context.getName(), true);30 }31}32public class TestNGListener implements IClassListener {33 public void onBeforeClass(ITestClass testClass) {34 Reporter.log("Before class: " + testClass.getName(), true);35 }36 public void onAfterClass(ITestClass testClass) {37 Reporter.log("After class: " + testClass.getName(), true);38 }39}40public class TestNGListener implements IInvokedMethodListener {41 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {42 Reporter.log("Before invocation: " + testResult.getTestClass().getName()43 + " => " + method.getTestMethod().getMethodName(), true);44 }45 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {46 Reporter.log("After invocation: " + testResult.getTestClass().getName()47 + " => " + method.getTestMethod().getMethodName(),
Interface ISuiteListener
Using AI Code Generation
1public class TestNGListener implements ISuiteListener {2 public void onStart(ISuite suite) {3 System.out.println("Start of execution of suite " + suite.getName());4 }5 public void onFinish(ISuite suite) {6 System.out.println("End of suite " + suite.getName());7 }8}9public class TestNGListener implements ITestListener {10 public void onTestStart(ITestResult result) {11 System.out.println("The execution of the main test starts now");12 }13 public void onTestSuccess(ITestResult result) {14 System.out.println("The main test passed");15 }16 public void onTestFailure(ITestResult result) {17 System.out.println("The main test failed");18 }19 public void onTestSkipped(ITestResult result) {20 System.out.println("The main test skipped");21 }22 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {23 System.out.println("The main test failed but within success percentage");24 }25 public void onStart(ITestContext context) {26 System.out.println("Start of execution of main test");27 }28 public void onFinish(ITestContext context) {29 System.out.println("End of execution of main test");30 }31}32public class TestNGListener implements IInvokedMethodListener {33 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {34 System.out.println("Before Invocation of method " + method.getTestMethod().getMethodName());35 }36 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {37 System.out.println("After Invocation of method " + method.getTestMethod().getMethodName());38 }39}40public class TestNGListener implements IAnnotationTransformer {41 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {42 annotation.setRetryAnalyzer(RetryAnalyzer.class);43 }44}45public class TestNGListener implements IExecutionListener {46 public void onExecutionStart() {47 System.out.println("Start of execution of test");48 }49 public void onExecutionFinish() {50 System.out.println("End of execution of test");51 }52}
Interface ISuiteListener
Using AI Code Generation
1package com.test;2import org.testng.ISuite;3import org.testng.ISuiteListener;4import org.testng.ITestContext;5import org.testng.ITestListener;6import org.testng.ITestResult;7public class TestNGListeners implements ITestListener, ISuiteListener {8 public void onFinish(ISuite suite) {9 System.out.println("onFinish method of ISuiteListener");10 }11 public void onStart(ISuite suite) {12 System.out.println("onStart method of ISuiteListener");13 }14 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {15 System.out.println("onTestFailedButWithinSuccessPercentage method of ITestListener");16 }17 public void onTestFailure(ITestResult result) {18 System.out.println("onTestFailure method of ITestListener");19 }20 public void onTestSkipped(ITestResult result) {21 System.out.println("onTestSkipped method of ITestListener");22 }23 public void onTestStart(ITestResult result) {24 System.out.println("onTestStart method of ITestListener");25 }26 public void onTestSuccess(ITestResult result) {27 System.out.println("onTestSuccess method of ITestListener");28 }29 public void onFinish(ITestContext context) {30 System.out.println("onFinish method of ITestListener");31 }32 public void onStart(ITestContext context) {33 System.out.println("onStart method of ITestListener");34 }35}
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!!