Best Testng code snippet using org.testng.Interface IInvokedMethod.isTestMethod
Source:SeleniumGridListener.java  
...82                return;83            }84            // For non-session sharing, we only allow our annotation(s) on @Test methods.85            // When this condition is true, we allow the session be created.86            if (!method.isTestMethod() && !isSeLionAnnotatedTestClass(method)) {87                return;88            }89            // For session sharing, we only allow our annotation on the class.90            // In this case the session can only be created in the @Test with the highest priority (first test, smallest91            // number) or in a @BeforeClass92            if (isSeLionAnnotatedTestClass(method)) {93                if (!isValidBeforeCondition(method)) {94                    return;95                }96                // For session sharing, we need to ensure @Test methods are priority based.97                if (method.isTestMethod()) {98                    // we need to ensure each @Test method is annotated99                    if (isLowPriority(method)) {100                        // For session sharing tests, Need to create new session only for Test (Web or Mobile) with101                        // highest priority (first test, smallest number) in the class.102                        testSessionSharingRules(method);103                    } else {104                        return;105                    }106                }107            }108            // Abort if there is already an instance of AbstractTestSession at this point.109            if (Grid.getTestSession() != null) {110                return;111            }112            AbstractTestSession testSession = TestSessionFactory.newInstance(method);113            Grid.getThreadLocalTestSession().set(testSession);114            InvokedMethodInformation methodInfo = TestNGUtils.getInvokedMethodInformation(method, testResult);115            testSession.initializeTestSession(methodInfo);116            if (!(testSession instanceof BasicTestSession)) {117                // BasicTestSession are non selenium tests. So no need to start the Local hub.118                try {119                    LocalGridManager.spawnLocalHub(testSession);120                } catch (NoClassDefFoundError e) {121                    logger.log(Level.SEVERE, "You are trying to run a local server but are missing Jars. Do you have "122                            + "SeLion-Grid and Selenium-Server in your CLASSPATH?", e);123                    // No sense in continuing ... SELENIUM_RUN_LOCALLY is a global config property124                    System.exit(1); // NOSONAR125                }126            }127        } catch (Exception e) { // NOSONAR128            if (e instanceof RuntimeException) {129                throw e;130            }131            // convert the checked exception into a runtime exception.132            throw new RuntimeException(e.getMessage(), e);133        }134        logger.exiting();135    }136    private boolean isSeLionAnnotatedTestClass(IInvokedMethod method) {137        Class<?> cls = method.getTestMethod().getInstance().getClass();138        final boolean isWebTestClass = cls.getAnnotation(WebTest.class) != null;139        final boolean isMobileTestClass = cls.getAnnotation(MobileTest.class) != null;140        return isMobileTestClass || isWebTestClass;141    }142    private boolean isValidBeforeCondition(IInvokedMethod method) {143        if (method.isTestMethod()) {144            return true;145        }146        return method.getTestMethod().isBeforeClassConfiguration();147    }148    private void testSessionSharingRules(IInvokedMethod method) {149        Test t = method.getTestMethod().getInstance().getClass().getAnnotation(Test.class);150        if (t != null && t.singleThreaded()) {151            if (!isPriorityUnique(method)) {152                throw new IllegalStateException(153                        "All the session sharing test methods within the same class should have a unique priority.");154            } else {155                return;156            }157        }158        throw new IllegalStateException(159                "Session sharing test should have a class level @Test annotation with the property singleThreaded = true defined.");160    }161    private boolean isLowPriority(IInvokedMethod method) {162        int low = method.getTestMethod().getPriority();163        for (ITestNGMethod test : method.getTestMethod().getTestClass().getTestMethods()) {164            // ensures all test methods have the @Test annotation. Throw exception if that's not the case165            if (!isAnnotatedWithTest(test.getConstructorOrMethod().getMethod())) {166                throw new IllegalStateException(167                        "Session sharing requires all test methods to define a priority via the @Test annotation.");168            }169            if (test.getEnabled() && test.getPriority() < low) {170                return false;171            }172        }173        Test t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);174        // If there is an existing session and the test method has a DP then don't create a session175        // For a data driven test method with the first data the session must be created176        // Hence return true if currentInvocationCount is 1 otherwise utilize the same session177        // by returning false178        int currentInvocationCount = method.getTestMethod().getCurrentInvocationCount();179        if (!t.dataProvider().isEmpty()) {180            return currentInvocationCount == 0;181        }182        return true;183    }184    private boolean isHighPriority(IInvokedMethod method) {185        if (!isAnnotatedWithTest(method)) {186            // Abort. There will already be an exception thrown in isLowPriority for this case.187            return true;188        }189        int high = method.getTestMethod().getPriority();190        for (ITestNGMethod test : method.getTestMethod().getTestClass().getTestMethods()) {191            if (test.getEnabled() && test.getPriority() > high) {192                return false;193            }194        }195        Test t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);196        // For a test method with a data provider197        if (!(t.dataProvider().isEmpty())) {198            int currentInvocationCount = method.getTestMethod().getCurrentInvocationCount();199            int parameterInvocationCount = method.getTestMethod().getParameterInvocationCount();200            // If the data set from the data provider is exhausted201            // It means its the last method with the data provider- this is the exit condition202            return (currentInvocationCount == parameterInvocationCount);203        }204        return true;205    }206    private boolean isAnnotatedWithTest(IInvokedMethod method) {207        return isAnnotatedWithTest(method.getTestMethod().getConstructorOrMethod().getMethod());208    }209    private boolean isAnnotatedWithTest(Method method) {210        Test t = method.getAnnotation(Test.class);211        return t != null;212   }213    private boolean isPriorityUnique(IInvokedMethod method) {214        // Logic to check priorities of all test methods are unique. This is used in Session Sharing.215        Set<Integer> check = new HashSet<Integer>();216        int length = method.getTestMethod().getTestClass().getTestMethods().length;217        int expectedSize = 0;218        for (int i = 0; i < length; i++) {219            //ignore @Test(enabled = false) methods220            if (!method.getTestMethod().getTestClass().getTestMethods()[i].getEnabled()) {221                continue;222            }223            check.add(method.getTestMethod().getTestClass().getTestMethods()[i].getPriority());224            expectedSize += 1;225            if (check.size() != expectedSize) {226                return false;227            }228        }229        return true;230    }231    /**232     * Executes when test case is finished<br>233     * 234     * Identify if webtest wants to have session open, otherwise close session<br>235     * <b>sample</b><br>236     * @webtest(browser="*firefox", <b>keepSessionOpen = true</b>)<br>237     * Analyzes failure if any238     * 239     * @see org.testng.IInvokedMethodListener#afterInvocation(org.testng.IInvokedMethod, org.testng.ITestResult)240     * 241     */242    @Override243    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {244        logger.entering(new Object[] { method, testResult });245        try {246            if (ListenerManager.isCurrentMethodSkipped(this)) {247                logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);248                return;249            }250            // Abort at this point, if there is no AbstractTestSession instance.251            if (Grid.getTestSession() == null) {252                return;253            }254            // For non-session sharing, we only allow our annotation(s) on @Test methods.255            // When this condition is true, we allow the session to be closed.256            if (!method.isTestMethod() && !isSeLionAnnotatedTestClass(method)) {257                return;258            }259            // For session sharing, we only allow our annotation on the class.260            // In this case the session can only be closed in the @Test with the lowest priority (last test, biggest261            // number) or in an @AfterClass262            if (isSeLionAnnotatedTestClass(method)) {263                if (!isValidAfterCondition(method)) {264                    return;265                }266                if (method.isTestMethod() && hasValidAfterCondition(method)) {267                    return;268                }269                if (method.isTestMethod() && !isHighPriority(method)) {270                    // For session sharing tests, Need to close session only for Test (Web or Mobile) with highest271                    // priority (last test) in the class.272                    return;273                }274            }275            // let's attempt to capture a screenshot in case of failure from Selenium or SeLion PageObject276            // or when there was an assertion failure.277            // That way a user can see the how the page looked like when a test failed.278            if (testResult.getStatus() == ITestResult.FAILURE279                    && (testResult.getThrowable() instanceof WebDriverException ||280                    testResult.getThrowable() instanceof AssertionError)) {281                warnUserOfTestFailures(testResult);282            }283            AbstractTestSession testSession = Grid.getTestSession();284            testSession.closeSession();285            testResult.setAttribute(JsonRuntimeReporterHelper.IS_COMPLETED, true);286        } catch (Exception e) { // NOSONAR287            logger.log(Level.WARNING, "An error occurred while processing afterInvocation: " + e.getMessage(), e);288        }289        logger.exiting();290    }291    private boolean isValidAfterCondition(IInvokedMethod method) {292        return method.isTestMethod() || method.getTestMethod().isAfterClassConfiguration();293    }294    private boolean hasValidAfterCondition(IInvokedMethod method) {295        return method.getTestMethod().getTestClass().getAfterClassMethods().length > 0;296    }297    private void warnUserOfTestFailures(ITestResult testResult) {298        // don't bother if we don't have a session299        if (!Grid.getTestSession().isStarted()) {300            return;301        }302        // don't bother if we don't have a web or mobile test session303        if (!(Grid.getTestSession() instanceof MobileTestSession) &&304                !(Grid.getTestSession() instanceof WebTestSession)) {305            return;306        }...Source:VTAFTestListener.java  
...116     */117    @Override118    public final void afterInvocation(final IInvokedMethod method,119            final ITestResult result) {120        if (method.isTestMethod()) {121            if (result.getStatus() == ITestResult.SKIP) {122                endTestReporting("skipped");123            } else if (result.getStatus() == ITestResult.FAILURE) {124                endTestReporting("failed");125            } else if (result.getStatus() == ITestResult.SUCCESS) {126                endTestReporting("passed");127            }128129        }130131    }132133    /**134     * Before invocation.135     * 136     * @param methodtest137     *            the methodtest138     * @param result139     *            the result140     * @see org.testng.IInvokedMethodListener#beforeInvocation(org.testng.IInvokedMethod,141     *      org.testng.ITestResult)142     */143    @Override144    public final void beforeInvocation(final IInvokedMethod methodtest,145            final ITestResult result) {146147        if (methodtest.isTestMethod()) {148149            String dataProvider = "";150151            Method method =152                    methodtest.getTestMethod().getConstructorOrMethod()153                            .getMethod();154            Annotation[] testAnnot = method.getAnnotations();155            for (Annotation annot : testAnnot) {156157                if (annot instanceof Test) {158159                    Test tAnnot = (Test) annot;160                    dataProvider = tAnnot.dataProvider();161                    if ("".equalsIgnoreCase(prevDataProvider)
...Source:AbstractChainedListener.java  
...79    @Override80    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {81        if (method.getTestMethod().isBeforeMethodConfiguration()) {82            beforeMethodBefore.add(testResult.getName());83        } else if (method.isTestMethod()) {84            testMethodBefore.add(testResult.getName());85        } else if (method.getTestMethod().isAfterMethodConfiguration()) {86            afterMethodBefore.add(testResult.getName());87        }88    }89    @Override90    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {91        if (method.getTestMethod().isBeforeMethodConfiguration()) {92            beforeMethodAfter.add(testResult.getName());93        } else if (method.isTestMethod()) {94            testMethodAfter.add(testResult.getName());95        } else if (method.getTestMethod().isAfterMethodConfiguration()) {96            afterMethodAfter.add(testResult.getName());97        }98    }99    @Override100    public void onBeforeClass(ITestClass testClass) {101        beforeClass.add(testClass.getRealClass().getSimpleName());102    }103    @Override104    public void onAfterClass(ITestClass testClass) {105        afterClass.add(testClass.getRealClass().getSimpleName());106    }107    @Override...Source:MyTestNGAnnotationListener.java  
...26    boolean testSuccess = true;27    28    29    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {30        if(method.isTestMethod() && annotationPresent(method, MyTestNGAnnotation.class) ) {31            //System.out.println("This gets invoked before every TestNG Test that has @MyTestNGAnnotation Annotation...");32            //System.out.println("Name: " + DataSet.name + " City: " + DataSet.city + " State: " + DataSet.state);33        }34    }35    36    private boolean annotationPresent(IInvokedMethod method, Class clazz) {37        boolean retVal = method.getTestMethod().getConstructorOrMethod().getMethod().isAnnotationPresent(clazz) ? true : false;38        return retVal;39    }40    41    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {42        if(method.isTestMethod()) {43            if(method.getClass().isAnnotationPresent(MyTestNGAnnotation.class)) {44                System.out.println("This gets invoked after every TestNG Test that has @MyTestNGAnnotation Annotation...");45            }46            if( !testSuccess ) {47                testResult.setStatus(ITestResult.FAILURE);48            }49        }50    }51    public void onTestStart(ITestResult result) {52        // TODO Auto-generated method stub53        54    }55    public void onTestSuccess(ITestResult result) {56        // TODO Auto-generated method stub...Source:XrayListener.java  
...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) {...Source:ConnsTestListener.java  
...28	 */29	public void afterInvocation(IInvokedMethod method, ITestResult testResult) {30		Reporter.setCurrentTestResult(testResult);3132		if (method.isTestMethod()) {33			List<String> verificationFailures = SoftAssertor.getVerificationFailures();34			int size = verificationFailures.size();35			// if there are verification failures...36			if (size > 0) {37				// set the test to failed38				testResult.setStatus(ITestResult.FAILURE);39				testResult.setAttribute("ErrorMsg ", verificationFailures.toString());40				Reporter.log(verificationFailures.toString());41				// if there is an assertion failure add it to42				// verificationFailures43				if (testResult.getThrowable() != null) {44					verificationFailures.add(testResult.getThrowable().getMessage());45				}46				StringBuffer failureMsg = new StringBuffer();
...Source:InvokedMethodListenerImpl.java  
...10 * </p>11 */12public class InvokedMethodListenerImpl implements IInvokedMethodListener {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:IInvokedMethod.java  
...7public interface IInvokedMethod {8  /**9   * @return true if this method is a test method10   */11  public abstract boolean isTestMethod();12  /**13   * @return true if this method is a configuration method (@BeforeXXX or @AfterXXX)14   */15  public abstract boolean isConfigurationMethod();16  /**17   * @return the test method18   */19  public abstract ITestNGMethod getTestMethod();20  public ITestResult getTestResult();21  /**22   * @return the date when this method was run23   */24  public abstract long getDate();25}...isTestMethod
Using AI Code Generation
1import org.testng.IInvokedMethod;2import org.testng.IInvokedMethodListener;3import org.testng.ITestResult;4import org.testng.annotations.Test;5public class TestNGListener implements IInvokedMethodListener {6    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {7        if (method.isTestMethod()) {8            System.out.println("Test method " + testResult.getName() + " started");9        }10    }11    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {12        if (method.isTestMethod()) {13            System.out.println("Test method " + testResult.getName() + " finished");14        }15    }16}17public class TestNGListenerTest {18    public void testMethod1() {19        System.out.println("TestNGListenerTest -> testMethod1");20    }21    public void testMethod2() {22        System.out.println("TestNGListenerTest -> testMethod2");23    }24}25import org.testng.Assert;26import org.testng.annotations.Listeners;27import org.testng.annotations.Test;28@Listeners(TestNGListener.class)29public class TestNGListenerWithAnnotationTest {30    public void testMethod1() {31        Assert.assertTrue(false);32        System.out.println("TestNGListenerWithAnnotationTest -> testMethod1");33    }34    public void testMethod2() {35        System.out.println("TestNGListenerWithAnnotationTest -> testMethod2");36    }37}38import org.testng.Assert;39import org.testng.annotations.Test;40public class TestNGListenerWithoutAnnotationTest {41    public void testMethod1() {42        Assert.assertTrue(false);43        System.out.println("TestNGListenerWithoutAnnotationTest -> testMethod1");44    }45    public void testMethod2() {46        System.out.println("TestNGListenerWithoutAnnotationTest -> testMethod2");47    }48}49import org.testng.annotations.Test;50public class TestNGListenerWithoutTestNGListenerTest {51    public void testMethod1() {52        System.out.println("TestNGListenerWithoutTestNGListenerTest -> testMethod1");53    }54    public void testMethod2() {55        System.out.println("TestNGListenerWithoutTestNG 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!!
