Best Testng code snippet using org.testng.Interface IInvokedMethodListener
Source:InvokedMethodListenerInvoker.java
1package org.testng.internal.invokers;2import org.testng.IInvokedMethod;3import org.testng.IInvokedMethodListener;4import org.testng.IInvokedMethodListener2;5import org.testng.ITestContext;6import org.testng.ITestResult;7import org.testng.collections.Maps;8import java.util.Map;9import static org.testng.internal.invokers.InvokedMethodListenerMethod.AFTER_INVOCATION;10import static org.testng.internal.invokers.InvokedMethodListenerMethod.BEFORE_INVOCATION;11import static org.testng.internal.invokers.InvokedMethodListenerSubtype.EXTENDED_LISTENER;12import static org.testng.internal.invokers.InvokedMethodListenerSubtype.SIMPLE_LISTENER;13/**14 * Hides complexity of calling methods of {@link IInvokedMethodListener} and15 * {@link IInvokedMethodListener2}.16 *17 * @author Ansgar Konermann18 */19public class InvokedMethodListenerInvoker {20 private InvokedMethodListenerMethod m_listenerMethod;21 private ITestContext m_testContext;22 private ITestResult m_testResult;23 /**24 * Creates a new invoker instance which can be used to call the specified {@code listenerMethod}25 * on any number of {@link IInvokedMethodListener}s.26 *27 * @param listenerMethod method which should be called28 * @param testResult test result which should be passed to the listener method upon invocation29 * @param testContext test context which should be passed to the listener method upon invocation.30 * This parameter is only used when calling methods on an {@link IInvokedMethodListener2}.31 */32 public InvokedMethodListenerInvoker(InvokedMethodListenerMethod listenerMethod,33 ITestResult testResult, ITestContext testContext) {34 m_listenerMethod = listenerMethod;35 m_testContext = testContext;36 m_testResult = testResult;37 }38 /**39 * Invoke the given {@code listenerInstance}, calling the method specified in the constructor of40 * this {@link InvokedMethodListenerInvoker}.41 *42 * @param listenerInstance the listener instance which should be invoked.43 * @param invokedMethod the {@link IInvokedMethod} instance which should be passed to the44 * {@link IInvokedMethodListener#beforeInvocation(IInvokedMethod, ITestResult)},45 * {@link IInvokedMethodListener#afterInvocation(IInvokedMethod, ITestResult)},46 * {@link IInvokedMethodListener2#beforeInvocation(IInvokedMethod, ITestResult, ITestContext)}47 * or {@link IInvokedMethodListener2#afterInvocation(IInvokedMethod, ITestResult, ITestContext)}48 * method.49 */50 @SuppressWarnings("unchecked")51 public void invokeListener(IInvokedMethodListener listenerInstance,52 IInvokedMethod invokedMethod) {53 final InvocationStrategy strategy = obtainStrategyFor(listenerInstance, m_listenerMethod);54 strategy.callMethod(listenerInstance, invokedMethod, m_testResult, m_testContext);55 }56 private InvocationStrategy obtainStrategyFor(IInvokedMethodListener listenerInstance,57 InvokedMethodListenerMethod listenerMethod) {58 InvokedMethodListenerSubtype invokedMethodListenerSubtype = InvokedMethodListenerSubtype59 .fromListener(listenerInstance);60 Map<InvokedMethodListenerMethod, InvocationStrategy> strategiesForListenerType = strategies61 .get(invokedMethodListenerSubtype);62 InvocationStrategy invocationStrategy = strategiesForListenerType.get(listenerMethod);63 return invocationStrategy;64 }65 private static interface InvocationStrategy<LISTENER_TYPE extends IInvokedMethodListener> {66 void callMethod(LISTENER_TYPE listener, IInvokedMethod invokedMethod, ITestResult testResult,67 ITestContext testContext);68 }69 private static class InvokeBeforeInvocationWithoutContextStrategy implements70 InvocationStrategy<IInvokedMethodListener> {71 public void callMethod(IInvokedMethodListener listener, IInvokedMethod invokedMethod,72 ITestResult testResult, ITestContext testContext) {73 listener.beforeInvocation(invokedMethod, testResult);74 }75 }76 private static class InvokeBeforeInvocationWithContextStrategy implements77 InvocationStrategy<IInvokedMethodListener2> {78 public void callMethod(IInvokedMethodListener2 listener, IInvokedMethod invokedMethod,79 ITestResult testResult, ITestContext testContext) {80 listener.beforeInvocation(invokedMethod, testResult, testContext);81 }82 }83 private static class InvokeAfterInvocationWithoutContextStrategy implements84 InvocationStrategy<IInvokedMethodListener> {85 public void callMethod(IInvokedMethodListener listener, IInvokedMethod invokedMethod,86 ITestResult testResult, ITestContext testContext) {87 listener.afterInvocation(invokedMethod, testResult);88 }89 }90 private static class InvokeAfterInvocationWithContextStrategy implements91 InvocationStrategy<IInvokedMethodListener2> {92 public void callMethod(IInvokedMethodListener2 listener, IInvokedMethod invokedMethod,93 ITestResult testResult, ITestContext testContext) {94 listener.afterInvocation(invokedMethod, testResult, testContext);95 }96 }97 private static final Map<InvokedMethodListenerSubtype, Map<InvokedMethodListenerMethod,98 InvocationStrategy>> strategies = Maps.newHashMap();99 private static final Map<InvokedMethodListenerMethod, InvocationStrategy>100 INVOKE_WITH_CONTEXT_STRATEGIES = Maps.newHashMap();101 private static final Map<InvokedMethodListenerMethod, InvocationStrategy>102 INVOKE_WITHOUT_CONTEXT_STRATEGIES = Maps.newHashMap();103 static {104 INVOKE_WITH_CONTEXT_STRATEGIES.put(BEFORE_INVOCATION,105 new InvokeBeforeInvocationWithContextStrategy());106 INVOKE_WITH_CONTEXT_STRATEGIES.put(AFTER_INVOCATION,107 new InvokeAfterInvocationWithContextStrategy());108 INVOKE_WITHOUT_CONTEXT_STRATEGIES.put(BEFORE_INVOCATION,109 new InvokeBeforeInvocationWithoutContextStrategy());110 INVOKE_WITHOUT_CONTEXT_STRATEGIES.put(AFTER_INVOCATION,111 new InvokeAfterInvocationWithoutContextStrategy());112 strategies.put(EXTENDED_LISTENER, INVOKE_WITH_CONTEXT_STRATEGIES);113 strategies.put(SIMPLE_LISTENER, INVOKE_WITHOUT_CONTEXT_STRATEGIES);114 }115}...
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:XrayListener.java
1package components.reporting.xray;2import components.testbase.*;3import org.testng.*;4/**5 * The listener interface for receiving Xray events.6 * The Listener can be automatically invoked when TestNG tests are run by using ServiceLoader mechanism.7 * You can also add this listener to a TestNG Test class by adding8 * <code>@Listeners({com.xpand.java.XrayAnnotationListener.class})</code>9 * before the test class10 *11 * @see Xray12 */13public class XrayListener extends TestBase implements IInvokedMethodListener, ITestListener {14 boolean testSuccess = true;15 /* (non-Javadoc)16 * @see org.testng.IInvokedMethodListener#beforeInvocation(org.testng.IInvokedMethod, org.testng.ITestResult)17 */18 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {19 if(method.isTestMethod() && annotationPresent(method, Xray.class) ) {20 testResult.setAttribute("requirement", method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Xray.class).requirement());21 testResult.setAttribute("test", method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Xray.class).test());22 testResult.setAttribute("labels", method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Xray.class).labels());23 }24 }25 private boolean annotationPresent(IInvokedMethod method, Class clazz) {26 boolean retVal = method.getTestMethod().getConstructorOrMethod().getMethod().isAnnotationPresent(clazz) ? true : false;27 return retVal;28 }29 /* (non-Javadoc)30 * @see org.testng.IInvokedMethodListener#afterInvocation(org.testng.IInvokedMethod, org.testng.ITestResult)31 */32 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {33 if(method.isTestMethod()) {34 if( !testSuccess ) {35 testResult.setStatus(ITestResult.FAILURE);36 testResult.setAttribute("env",System.getProperty("testedEnv"));37 testResult.setAttribute("version",System.getProperty("ActualVersion"));38 }39 }40 }41 public void onTestStart(ITestResult result) {42 // TODO Auto-generated method stub43 }44 public void onTestSuccess(ITestResult result) {45 // TODO Auto-generated method stub46 }47 public void onTestFailure(ITestResult result) {48 // TODO Auto-generated method stub49 }50 public void onTestSkipped(ITestResult result) {51 // TODO Auto-generated method stub52 }53 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {54 // TODO Auto-generated method stub55 }56 public void onStart(ITestContext context) {57 }58 public void onFinish(ITestContext context) {59 // TODO Auto-generated method stub60 }61}...
Source:SauceLabsIntegration.java
1package omelet.support.saucelabs;2import omelet.driver.Driver;3import org.apache.log4j.Logger;4import org.openqa.selenium.remote.RemoteWebDriver;5import org.testng.IInvokedMethod;6import org.testng.IInvokedMethodListener;7import org.testng.ITestResult;8import org.testng.Reporter;9public class SauceLabsIntegration implements IInvokedMethodListener {10 private static final Logger LOGGER = Logger11 .getLogger(SauceLabsIntegration.class);12 @Override13 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {14 try {15 // it will throw Null pointer exception for the method who are not16 // omelet driven , should be fixed as using try catch is a temporary17 // one!18 if (Driver.getBrowserConf().host().contains("sauce")19 && Driver.getBrowserConf().isRemoteFlag()) {20 RemoteWebDriver driver = (RemoteWebDriver) Driver.getDriver();21 LOGGER.debug("After in SL Integration driver Session ID: "22 + driver.getSessionId());23 WebInterface slWebInterface = new WebInterface();24 slWebInterface.updateSauceLabsJob(driver.getSessionId()25 .toString(), method.getTestMethod().getMethodName(),26 method.getTestResult().isSuccess());27 Reporter.setCurrentTestResult(testResult);28 Reporter.log("SauceLabs Report :: ");29 Reporter.log(slWebInterface.generateLinkForJob(driver30 .getSessionId().toString()));31 // Reporter.log(slWebInterface.generateLinkForEmbedScript(driver32 // .getSessionId().toString(), true));33 // Reporter.log("<br>");34 // Reporter.log("SauceLabs Video :: "35 // + slWebInterface.generateLinkForEmbedScript(driver36 // .getSessionId().toString(), false));37 Reporter.log("<br>");38 }39 } catch (Exception e) {40 LOGGER.error("Not to interfere in the test result!, but needs to be taken care!");41 }42 }43 @Override44 public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) {45 }46}...
Source:InvokedMethodListenerSubtype.java
1package org.testng.internal.invokers;2import org.testng.IInvokedMethodListener;3import org.testng.IInvokedMethodListener2;4import org.testng.TestNGException;5/**6 * Indicates whether a {@link InvokedMethodListenerMethod} is to be called on a simple or an7 * extended invoked method listener. All {@link IInvokedMethodListener}s are considered8 * {@link #SIMPLE_LISTENER}, instances of {@link IInvokedMethodListener2} are all considered9 * {@link #EXTENDED_LISTENER}.10 *11 * @author Ansgar Konermann12 */13enum InvokedMethodListenerSubtype {14 EXTENDED_LISTENER(IInvokedMethodListener2.class),15 SIMPLE_LISTENER(IInvokedMethodListener.class);16 private Class<? extends IInvokedMethodListener> m_matchingInterface;17 private InvokedMethodListenerSubtype(Class<? extends IInvokedMethodListener> listenerClass) {18 m_matchingInterface = listenerClass;19 }20 private boolean isInstance(IInvokedMethodListener listenerInstance) {21 return m_matchingInterface.isInstance(listenerInstance);22 }23 public static InvokedMethodListenerSubtype fromListener(IInvokedMethodListener listenerInstance) {24 if (EXTENDED_LISTENER.isInstance(listenerInstance)) {25 return EXTENDED_LISTENER;26 }27 else if (SIMPLE_LISTENER.isInstance(listenerInstance)) {28 return SIMPLE_LISTENER;29 }30 throw new TestNGException("Illegal " + IInvokedMethodListener.class.getSimpleName()31 + " instance: " + listenerInstance.getClass().getName() + ".");32 }33}...
Source:IInvokedMethodListenerEx.java
1package com.nordstrom.automation.testng;23import org.testng.IInvokedMethod;4import org.testng.IInvokedMethodListener;5import org.testng.ITestResult;67/**8 * This interface extends {@link IInvokedMethodListener} without adding any new method signatures. While any class that9 * implements {@link IInvokedMethodListenerEx} can be activated as an invoked method listener, the intended target for10 * this interface is test classes whose execution will be orchestrated by {@link ExecutionFlowController}. During test11 * execution, the execution flow controller forwards calls received by its own {@link #beforeInvocation(IInvokedMethod,12 * ITestResult)} and {@link #afterInvocation(IInvokedMethod, ITestResult)} implementations to those of the test class.13 * 14 * @see ExecutionFlowController15 * @see IInvokedMethodListener16 */17public interface IInvokedMethodListenerEx extends IInvokedMethodListener {1819}
...
Interface IInvokedMethodListener
Using AI Code Generation
1import org.testng.IInvokedMethod;2import org.testng.IInvokedMethodListener;3import org.testng.ITestResult;4import org.testng.annotations.Test;5public class TestNGListenerDemo implements IInvokedMethodListener {6 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {7 System.out.println("About to begin executing following method : " + testResult.getTestClass().getName() + " => " + method.getTestMethod().getMethodName());8 }9 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {10 System.out.println("Completed executing following method : " + testResult.getTestClass().getName() + " => " + method.getTestMethod().getMethodName());11 }12}13import org.testng.ITestContext;14import org.testng.ITestListener;15import org.testng.ITestResult;16public class TestNGListenerDemo implements ITestListener {17 public void onFinish(ITestContext result) {18 System.out.println("Test Suite execution is finished.");19 }20 public void onStart(ITestContext result) {21 System.out.println("Test Suite execution is started.");22 }23 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {24 System.out.println("onTestFailedButWithinSuccessPercentage for " + result.getMethod().getMethodName());25 }26 public void onTestFailure(ITestResult result) {27 System.out.println("onTestFailure for " + result.getMethod().getMethodName());28 }29 public void onTestSkipped(ITestResult result) {30 System.out.println("onTestSkipped for " + result.getMethod().getMethodName());31 }32 public void onTestStart(ITestResult result) {33 System.out.println("onTestStart for " + result.getMethod().getMethodName());34 }35 public void onTestSuccess(ITestResult result) {36 System.out.println("onTestSuccess for " + result.getMethod().getMethodName());37 }38}39import org.testng.ISuite;40import org.testng.ISuiteListener;41public class TestNGListenerDemo implements ISuiteListener {42 public void onFinish(ISuite suite) {
Interface IInvokedMethodListener
Using AI Code Generation
1package com.testng;2import org.testng.IInvokedMethod;3import org.testng.IInvokedMethodListener;4import org.testng.ITestResult;5import org.testng.annotations.Test;6public class TestNGListener implements IInvokedMethodListener {7 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {8 System.out.println("Before Invocation of Method :"+method.getTestMethod().getMethodName());9 }10 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {11 System.out.println("After Invocation of Method :"+method.getTestMethod().getMethodName());12 }13}14package com.testng;15import org.testng.annotations.Listeners;16import org.testng.annotations.Test;17@Listeners(com.testng.TestNGListener.class)18public class TestNG {19 public void test1()20 {21 System.out.println("Test 1");22 }23 public void test2()24 {25 System.out.println("Test 2");26 }27 public void test3()28 {29 System.out.println("Test 3");30 }31}32public void onTestStart(ITestResult result);33public void onTestSuccess(ITestResult result);34public void onTestFailure(ITestResult result);35public void onTestSkipped(ITestResult result);36public void onTestFailedButWithinSuccessPercentage(ITestResult result);37public void onStart(ITestContext context);38public void onFinish(ITestContext context);
Interface IInvokedMethodListener
Using AI Code Generation
1public class TestNGListeners implements IInvokedMethodListener {2public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {3String textMsg = "About to begin executing following method : " + returnMethodName(method.getTestMethod());4System.out.println(textMsg);5ExtentTestManager.getTest().log(LogStatus.INFO, textMsg);6}7public void afterInvocation(IInvokedMethod method, ITestResult testResult) {8String textMsg = "Completed executing following method : " + returnMethodName(method.getTestMethod());9System.out.println(textMsg);10ExtentTestManager.getTest().log(LogStatus.INFO, textMsg);11}12private String returnMethodName(ITestNGMethod method) {13return method.getRealClass().getSimpleName() + "." + method.getMethodName();14}15}16package com.qa.testbase; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; public class ExtentTestManager { static ExtentReports extent = ExtentManager.getReporter(); static ExtentTest test; public static synchronized ExtentTest getTest() { return test; } public static synchronized void endTest() { extent.endTest(test); } public static synchronized ExtentTest startTest(String testName, String desc) { test = extent.startTest(testName, desc); return test; } }
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!!