Best Testng code snippet using org.testng.Interface IInvokedMethodListener.afterInvocation
...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,...
Source: XrayListener.java
...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 }...
Source: InvokedMethodListenerImpl.java
...13 @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {14 LogUtils.info('[' + getClass().getSimpleName() + " - beforeInvocation] - isTestMethod: " + method.isTestMethod()15 + " - ITestResult:" + testResult.getName());16 }17 @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) {18 LogUtils.info('[' + getClass().getSimpleName() + " - afterInvocation] - isTestMethod: " + method.isTestMethod()19 + " - ITestResult:" + testResult.getName());20 }21}...
Source: IInvokedMethodListenerEx.java
...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}
...
Source: CustomListener1.java
...12 System.out.println("beforeInvocation: " + testResult.getTestClass().getName() + 13 " => " + method.getTestMethod().getMethodName() );14 }15 @Override16 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {17 System.out.println("AfterInvocation: " + testResult.getTestClass().getName() + 18 " => " + method.getTestMethod().getMethodName() );19 }20}...
afterInvocation
Using AI Code Generation
1import org.testng.IInvokedMethod;2import org.testng.IInvokedMethodListener;3import org.testng.ITestResult;4public class TestNGListener implements IInvokedMethodListener {5 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {6 if(method.isTestMethod()){7 System.out.println("Test is finished: " + testResult.getStatus());8 }9 }10 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {11 if(method.isTestMethod()){12 System.out.println("Test is started: " + testResult.getStatus());13 }14 }15}16[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ TestNGListener ---17[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ TestNGListener ---18[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ TestNGListener ---19[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ TestNGListener ---20[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ TestNGListener ---
afterInvocation
Using AI Code Generation
1package org.testng;2import org.testng.internal.annotations.IAnnotationFinder;3import org.testng.xml.XmlTest;4public interface IInvokedMethodListener extends ITestNGListener {5 void beforeInvocation(IInvokedMethod method, ITestResult testResult);6 void afterInvocation(IInvokedMethod method, ITestResult testResult);7}8package org.testng;9public interface IInvokedMethod {10 ITestNGMethod getTestMethod();11 ITestResult getTestResult();12}
afterInvocation
Using AI Code Generation
1import java.io.File;2import java.io.IOException;3import java.util.ArrayList;4import java.util.Date;5import java.util.List;6import org.testng.IInvokedMethod;7import org.testng.IInvokedMethodListener;8import org.testng.ITestResult;9import org.testng.TestListenerAdapter;10import com.aventstack.extentreports.ExtentReports;11import com.aventstack.extentreports.ExtentTest;12import com.aventstack.extentreports.MediaEntityBuilder;13import com.aventstack.extentreports.Status;14import com.aventstack.extentreports.reporter.ExtentHtmlReporter;15import com.aventstack.extentreports.reporter.configuration.Theme;16public class ExtentReportListener extends TestListenerAdapter implements IInvokedMethodListener{17 private static ExtentReports extent = ExtentManager.createInstance();18 private static ThreadLocal<ExtentTest> test = new ThreadLocal<ExtentTest>();19 private static String reportFileName = "ExtentReportResults.html";20 private static String fileSeperator = System.getProperty("file.separator");21 private static String reportFilepath = System.getProperty("user.dir") + fileSeperator + "test-output";22 private static String reportFileLocation = reportFilepath + fileSeperator + reportFileName;23 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {24 String textMsg = "About to begin executing following method : " + returnMethodName(method.getTestMethod().getMethodName());25 ExtentTest extentTest = test.get();26 extentTest.log(Status.INFO, textMsg);27 }28 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {29 String textMsg = "Completed executing following method : " + returnMethodName(method.getTestMethod().getMethodName());30 ExtentTest extentTest = test.get();31 extentTest.log(Status.INFO, textMsg);32 if(testResult.getThrowable() != null) {33 extentTest.log(Status.FAIL, testResult.getThrowable());34 }35 else {36 if(testResult.getStatus() == ITestResult.SUCCESS) {37 extentTest.log(Status.PASS, "Test passed");38 }39 else if(testResult.getStatus() == ITestResult.SKIP) {40 extentTest.log(Status.SKIP, "
Getting sequential logs while executing tests in parallel
Is there a Maven "compiler-only" scope for dependency artifacts
WebDriverException: unknown error: failed to change window state to maximized, current state is normal with Chrome 70 & Chromedriver 2.43 on MAC OS X
How to run multiple test classes in testng suite with only one web driver instance?
How do I test expectedExceptionsMessageRegExp (exception message) using TestNG?
TestNG dependsOnMethods from different class
TestNG- pass parameters to the constructor where parameters are decided based on the testname
set up an application with a database - tapestry-hibernate fail
Skip one maven test does not work
How to create a executable jar file for Testng and the runnnig point should be the Xml file
When you enable parallel then there will be some time between the beforeInvocation
and afterInvocation
in the logs as you have noticed and that difference in time varies from test to test hence the staggered output.
If what you want is the start and end messages next to each other then you are basically throwing out the time factor and as such can simply add your beforeInvocation
message to the afterInvocation
method as follows:
public class TestExecutionListener implements IInvokedMethodListener {
@Override
public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
}
@Override
public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
System.out.println("Testing : " + iInvokedMethod.getTestMethod().getMethodName());
System.out.println("Successfully Tested : " + iInvokedMethod.getTestMethod().getMethodName());
}
}
IMO this is the only way to do it as per your spec. However, if there is other information that must be gathered during the tests then perhaps you could buffer some logs in the TestExecutionListener
for example:
public class TestExecutionListener implements IInvokedMethodListener {
private Map<Integer, Deque<String>> logsMap = new HashMap<Integer, Deque<String>>();
public void log(IInvokedMethod iInvokedMethod, String log) {
if(!logsMap.containsKey(iInvokedMethod.getId())) {
logsMap.put(iInvokedMethod.getId(), new ArrayDeque<String>());
}
logsMap.get(iInvokedMethod.getId()).add(log);
}
@Override
public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
log(iInvokedMethod, "Testing : " + iInvokedMethod.getTestMethod().getMethodName());
}
@Override
public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
log(iInvokedMethod, "Successfully Tested : " + iInvokedMethod.getTestMethod().getMethodName());
Deque<String> logs = logsMap.get(iInvokedMethod.getId());
while(!logs.isEmpty()) {
System.out.println(logs.poll());
}
}
}
Check out the latest blogs from LambdaTest on this topic:
Cross browser testing has been a type of testing which requires a tremendous amount of effort and time. The process of testing your web-app over different browsers, operating systems, devices, screen resolutions to evaluate the rendering of your web content for a variety of your audience is an activity. Especially, if approached manually. Automated cross browser testing with Selenium can help you save the time of routine test activities, helping you cut short on regression testing. However, people seldom like changes. If manual testing is popular in your organization, the management will obviously raise questions when you ask them to implement test automation.
There are many debates going on whether testers should know programming languages or not. Everyone has his own way of backing the statement. But when I went on a deep research into it, I figured out that no matter what, along with soft skills, testers must know some programming languages as well. Especially those that are popular in running automation tests.
Being an open-source framework allowed Selenium to be compatible with multiple test automation frameworks for different programming languages and if we talk about Automation testing with Selenium and JavaScript, there is a particular framework that never fails to take the spotlight and that is the Nightwatch.js. This is why I decided to come up with Nightwatch.js tutorial for beginners.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Automation Testing Tutorial.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on JUnit Tutorial.
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!!