Source:Is it possible to put a condition to TestNG to run the test if that is member of two groups?
public MyFragment MyFragment(){
        return this;
    }
Best Testng code snippet using org.testng.Interface ITestContext
Source:ReflectionRecipesTest.java  
1package test.reflect;2import org.testng.Assert;3import org.testng.ITestContext;4import org.testng.ITestResult;5import org.testng.TestRunner;6import org.testng.annotations.DataProvider;7import org.testng.annotations.NoInjection;8import org.testng.annotations.Test;9import org.testng.internal.reflect.InjectableParameter;10import org.testng.internal.reflect.Parameter;11import org.testng.internal.reflect.ReflectionRecipes;12import org.testng.xml.XmlTest;13import java.lang.annotation.Retention;14import java.lang.annotation.Target;15import java.lang.reflect.InvocationTargetException;16import java.lang.reflect.Method;17import java.sql.Connection;18import java.util.ArrayList;19import java.util.Arrays;20import java.util.List;21import static java.lang.annotation.ElementType.METHOD;22import static java.lang.annotation.RetentionPolicy.RUNTIME;23/**24 * @author <a href="mailto:nitin.matrix@gmail.com">Nitin Verma</a>25 */26public class ReflectionRecipesTest {27  private static final Object[] A0 = new Object[]{343, true};28  private static final Parameter[] S0 = getMethodParameters(T.class, "s0");29  private static final Parameter[] S1 = getMethodParameters(T.class, "s1");30  private static final Parameter[] S2 = getMethodParameters(T.class, "s2");31  private static final Parameter[] S3 = getMethodParameters(T.class, "s3");32  private static Parameter[] getMethodParameters(final Class<?> clazz, final String methodName) {33    Method method = null;34    Parameter[] parameters = null;35    for (final Method m : clazz.getMethods()) {36      if (m.getName().equals(methodName)) {37        method = m;38      }39    }40    if (method != null) {41      parameters = ReflectionRecipes.getMethodParameters(method);42    }43    return parameters;44  }45  @DataProvider46  public Object[][] methodInputParameters() {47    return new Object[][]{S0, S1, S2, S3};48  }49  @DataProvider50  public Object[][] methodInputParamArgsPair() {51    return new Object[][]{52      new Object[]{S0, A0},53      new Object[]{S1, A0},54      new Object[]{S2, A0},55      new Object[]{S3, A0},56    };57  }58  @DataProvider59  public Object[][] exactMatchDP() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {60    final Method[] methods = ExactMatchTest.class.getDeclaredMethods();61    final List<Object[]> objects = new ArrayList<>();62    System.out.println("exactMatchDP:");63    for (int i = 0; i < methods.length; i++) {64      final Method method = methods[i];65      final ExactMatchTest.Expectation annotation =66        method.getAnnotation(ExactMatchTest.Expectation.class);67      if (annotation != null) {68        final String provider = annotation.expectationProvider();69        final int flag = annotation.flag();70        Assert.assertNotNull(provider);71        final Method providerMethod = ExactMatchTest.class.getMethod(provider, int.class);72        final Object out = providerMethod.invoke(ExactMatchTest.class, flag);73        Assert.assertTrue(out instanceof Object[][]);74        System.out.println(method.getName() + ", " + out);75        objects.add(new Object[]{out, method});76      }77    }78    return objects.toArray(new Object[objects.size()][]);79  }80  @DataProvider81  public Object[][] matchArrayEndingDP() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {82    final Method[] methods = MatchArrayEndingTest.class.getDeclaredMethods();83    final List<Object[]> objects = new ArrayList<>();84    System.out.println("matchArrayEndingDP:");85    for (int i = 0; i < methods.length; i++) {86      final Method method = methods[i];87      final MatchArrayEndingTest.Expectation annotation =88        method.getAnnotation(MatchArrayEndingTest.Expectation.class);89      if (annotation != null) {90        final String provider = annotation.expectationProvider();91        final int flag = annotation.flag();92        Assert.assertNotNull(provider);93        final Method providerMethod = MatchArrayEndingTest.class.getMethod(provider, int.class);94        final Object out = providerMethod.invoke(MatchArrayEndingTest.class, flag);95        Assert.assertTrue(out instanceof Object[][]);96        System.out.println(method.getName() + ", " + out);97        objects.add(new Object[]{out, method});98      }99    }100    return objects.toArray(new Object[objects.size()][]);101  }102  @DataProvider103  public Object[][] testContexts() {104    return new Object[][]{105      {TestRunner.class},106      {ITestContext.class},107      {TestContextJustForTesting.class}108    };109  }110  @DataProvider111  public Object[][] notTestContexts() {112    return new Object[][]{113      {Object.class},114      {Class.class},115      {Connection.class}116    };117  }118  @Test(dataProvider = "matchArrayEndingDP")119  public void matchArrayEndingTest(final Object[][] expected, @NoInjection final Method method) {120    if (expected != null) {121      final Parameter[] methodParameters = ReflectionRecipes.getMethodParameters(method);122      Assert.assertNotNull(methodParameters);123      final Parameter[] filteredParameters =124        ReflectionRecipes.filter(methodParameters, InjectableParameter.Assistant.ALL_INJECTS);125      Assert.assertNotNull(filteredParameters);126      for (final Object[] expect : expected) {127        Assert.assertNotNull(expect);128        Assert.assertEquals(expect.length, 2);129        Assert.assertNotNull(expect[0]);130        Assert.assertTrue(expect[0] instanceof Object[]);131        Assert.assertNotNull(expect[1]);132        Assert.assertTrue(expect[1] instanceof Boolean);133        Assert.assertEquals(134          ReflectionRecipes.matchArrayEnding(filteredParameters, (Object[]) expect[0]),135          expect[1]136        );137      }138    }139  }140  @Test(dataProvider = "exactMatchDP")141  public void exactMatchTest(final Object[][] expected, @NoInjection final Method method) {142    if (expected != null) {143      final Parameter[] methodParameters = ReflectionRecipes.getMethodParameters(method);144      Assert.assertNotNull(methodParameters);145      final Parameter[] filteredParameters =146        ReflectionRecipes.filter(methodParameters, InjectableParameter.Assistant.ALL_INJECTS);147      Assert.assertNotNull(filteredParameters);148      for (final Object[] expect : expected) {149        Assert.assertNotNull(expect);150        Assert.assertEquals(expect.length, 2);151        Assert.assertNotNull(expect[0]);152        Assert.assertTrue(expect[0] instanceof Object[]);153        Assert.assertNotNull(expect[1]);154        Assert.assertTrue(expect[1] instanceof Boolean);155        Assert.assertEquals(156          ReflectionRecipes.exactMatch(filteredParameters, (Object[]) expect[0]),157          expect[1]158        );159      }160    }161  }162  @Test(dataProvider = "methodInputParameters")163  public void testFilters(final Parameter[] parameters) {164    System.out.println("In: " + Arrays.asList(parameters));165    final Parameter[] parameters1 = ReflectionRecipes.filter(parameters, InjectableParameter.Assistant.ALL_INJECTS);166    System.out.println("Out: " + Arrays.asList(parameters1));167    Assert.assertEquals(parameters1.length, 2);168    Assert.assertEquals(parameters1[0].getType(), int.class);169    Assert.assertEquals(parameters1[1].getType(), Boolean.class);170  }171  @Test(dataProvider = "methodInputParamArgsPair")172  public void testInject(final Parameter[] parameters, final Object[] args) {173    System.out.println("In: " + Arrays.asList(parameters));174    System.out.println("args: " + Arrays.asList(args));175    final Object[] injectedArgs = ReflectionRecipes.inject(176      parameters, InjectableParameter.Assistant.ALL_INJECTS, args,177      null, null, null178    );179    System.out.println("injectedArgs: " + Arrays.asList(injectedArgs));180    Assert.assertEquals(injectedArgs.length, parameters.length);181  }182  @Test(dataProvider = "testContexts")183  public void testIsOrImplementsInterface(final Class<?> clazz) {184    Assert.assertTrue(ReflectionRecipes.isOrImplementsInterface(ITestContext.class, clazz));185  }186  @Test(dataProvider = "notTestContexts")187  public void testNegativeCaseIsOrImplementsInterface(final Class<?> clazz) {188    Assert.assertFalse(ReflectionRecipes.isOrImplementsInterface(ITestContext.class, clazz));189  }190  private static interface T {191    public void s0(TestContextJustForTesting testContext, int i, Boolean b);192    public void s1(int i, ITestContext iTestContext, Boolean b);193    public void s2(int i, Boolean b, ITestContext iTestContext);194    public void s3(ITestContext iTestContext1, int i, Boolean b, ITestContext iTestContext2);195  }196  public static abstract class ExactMatchTest {197    public static Object[][] exactMatchData(final int flag) {198      switch (flag) {199        case 0:200          return new Object[][]{201            new Object[]{new Object[]{}, true},202            new Object[]{new Object[]{1}, false},203            new Object[]{new Object[]{""}, false},204            new Object[]{new Object[]{1, ""}, false},205          };206        case 1:207          return new Object[][]{208            new Object[]{new Object[]{1}, true},209            new Object[]{new Object[]{}, false},210            new Object[]{new Object[]{""}, false},211            new Object[]{new Object[]{1, ""}, false},212            new Object[]{new Object[]{"", 1}, false},213          };214        default:215          return null;216      }217    }218    @Expectation(expectationProvider = "exactMatchData", flag = 0)219    public abstract void s0();220    @Expectation(expectationProvider = "exactMatchData", flag = 0)221    public abstract void s0(final ITestContext a0);222    @Expectation(expectationProvider = "exactMatchData", flag = 0)223    public abstract void s0(final ITestContext a0, final ITestResult a1);224    @Expectation(expectationProvider = "exactMatchData", flag = 0)225    public abstract void s0(final ITestContext a0, final ITestResult a1, final XmlTest a2);226    @Expectation(expectationProvider = "exactMatchData", flag = 0)227    public abstract void s0(final ITestContext a0, final ITestResult a1, final XmlTest a2, final Method a3);228    @Expectation(expectationProvider = "exactMatchData", flag = 1)229    public abstract void s1(final int a0);230    @Expectation(expectationProvider = "exactMatchData", flag = 1)231    public abstract void s1(final ITestContext a0, final int a1);232    @Expectation(expectationProvider = "exactMatchData", flag = 1)233    public abstract void s1(final ITestContext a0, final Integer a1, final ITestResult a2);234    @Expectation(expectationProvider = "exactMatchData", flag = 1)235    public abstract void s1(final int a0, final ITestContext a1, final ITestResult a2, final XmlTest a3);236    @Expectation(expectationProvider = "exactMatchData", flag = 1)237    public abstract void s1(final ITestContext a0, final ITestResult a1, final int a2,238                            final XmlTest a3, final Method a4);239    @Retention(RUNTIME)240    @Target({METHOD})241    public static @interface Expectation {242      public String expectationProvider();243      public int flag();244    }245  }246  public static abstract class MatchArrayEndingTest {247    public static Object[][] matchArrayEndingData(final int flag) {248      switch (flag) {249        case 0:250          return new Object[][]{251            new Object[]{new Object[]{10f, 2.1f}, true},252            new Object[]{new Object[]{10}, true},253            new Object[]{new Object[]{10d, ""}, false},254            new Object[]{new Object[]{1, ""}, false},255          };256        case 1:257          return new Object[][]{258            new Object[]{new Object[]{1, 10f, 2.1f}, true},259            new Object[]{new Object[]{}, false},260            new Object[]{new Object[]{""}, false},261            new Object[]{new Object[]{10f, "", 2.1f}, false},262            new Object[]{new Object[]{"", 10f, 2.1f}, false},263          };264        default:265          return null;266      }267    }268    @Expectation(expectationProvider = "matchArrayEndingData", flag = 0)269    public abstract void s0(final float... f);270    @Expectation(expectationProvider = "matchArrayEndingData", flag = 0)271    public abstract void s0(final float[] f, final ITestContext a0);272    @Expectation(expectationProvider = "matchArrayEndingData", flag = 0)273    public abstract void s0(final ITestContext a0, final float[] f, final ITestResult a1);274    @Expectation(expectationProvider = "matchArrayEndingData", flag = 0)275    public abstract void s0(final ITestContext a0, final ITestResult a1, final XmlTest a2, final float... f);276    @Expectation(expectationProvider = "matchArrayEndingData", flag = 0)277    public abstract void s0(final ITestContext a0, final ITestResult a1,278                            final XmlTest a2, final float[] f,279                            final Method a3);280    @Expectation(expectationProvider = "matchArrayEndingData", flag = 1)281    public abstract void s1(final int a0, final float... f);282    @Expectation(expectationProvider = "matchArrayEndingData", flag = 1)283    public abstract void s1(final ITestContext a0, final int a1, final float... f);284    @Expectation(expectationProvider = "matchArrayEndingData", flag = 1)285    public abstract void s1(final ITestContext a0, final Integer a1,286                            final ITestResult a2, final float... f);287    @Expectation(expectationProvider = "matchArrayEndingData", flag = 1)288    public abstract void s1(final int a0, final ITestContext a1, final ITestResult a2,289                            final float[] f, final XmlTest a3);290    @Expectation(expectationProvider = "matchArrayEndingData", flag = 1)291    public abstract void s1(final ITestContext a0, final ITestResult a1, final int a2,292                            final XmlTest a3, final float[] f, final Method a4);293    @Retention(RUNTIME)294    @Target({METHOD})295    public static @interface Expectation {296      public String expectationProvider();297      public int flag();298    }299  }300}...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:TapestryTestConstants.java  
1// Copyright 2007, 2010, 2013 The Apache Software Foundation2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package org.apache.tapestry5.test;15import com.thoughtworks.selenium.CommandProcessor;16import com.thoughtworks.selenium.Selenium;17import org.testng.ITestContext;18import org.testng.xml.XmlTest;19import java.lang.reflect.Method;20/**21 * Defins {@link ITestContext} attributes meaninful to Tapestry for controlling application startup and shutdown.22 */23public class TapestryTestConstants24{25    /**26     * {@link ITestContext} attribute holding an instance of {@link Selenium}.27     *28     * @see SeleniumTestCase#testStartup(org.testng.ITestContext, org.testng.xml.XmlTest)29     * @since 5.2.030     */31    public static final String SELENIUM_ATTRIBUTE = "tapestry.selenium";32    /**33     * {@link ITestContext} attribute holding an instance of {@link ErrorReporter}.34     *35     * @see SeleniumTestCase#testStartup(org.testng.ITestContext, org.testng.xml.XmlTest)36     * @since 5.2.037     */38    public static final String ERROR_REPORTER_ATTRIBUTE = "tapestry.error-reporter";39    /**40     * {@link ITestContext} attribute holding an instance of {@link ErrorReporter}, used41     * to shutdown Selenium and the Web Server at the end of the test.42     *43     * @since 5.2.244     */45    public static final String SHUTDOWN_ATTRIBUTE = "tapestry.shutdown";46    /**47     * The {@link ITestContext} attribute holding an instance of {@link CommandProcessor}, with48     * enhanced exception reporting control. This allows tests that wish to, to bypass the {@link Selenium} interface49     * and execute commands directly on the Selenium RC server.50     *51     * @since 5.2.052     */53    public static final String COMMAND_PROCESSOR_ATTRIBUTE = "tapestry.command-processor";54    /**55     * {@link ITestContext} attribute holding the application's base URL.56     *57     * @since 5.2.058     */59    public static final String BASE_URL_ATTRIBUTE = "tapestry.base-url";60    /**61     * {@link ITestContext} attribute updated to store the current test method62     * (as a {@link Method} instance).63     */64    public static final String CURRENT_TEST_METHOD_ATTRIBUTE = "tapestry.current-test-method";65    /**66     * {@link XmlTest} parameter holding an absolute or relative path to a web app67     * folder.68     */69    public static final String WEB_APP_FOLDER_PARAMETER = "tapestry.web-app-folder";70    /**71     * {@link XmlTest} parameter holding the context path.72     */73    public static final String CONTEXT_PATH_PARAMETER = "tapestry.context-path";74    /**75     * {@link XmlTest} parameter holding the web server port.76     */77    public static final String PORT_PARAMETER = "tapestry.port";78    /**79     * {@link XmlTest} parameter holding the web server ssl port.80     */81    public static final String SSL_PORT_PARAMETER = "tapestry.ssl-port";82    /**83     * {@link XmlTest} parameter holding the browser command to pass to Selenium.84     */85    public static final String BROWSER_START_COMMAND_PARAMETER = "tapestry.browser-start-command";86    /**87     * {@link XmlTest} parameter holding the servlet container to run for the integration tests.88     *89     * @since 5.390     */91    public static final String SERVLET_CONTAINER_PARAMETER = "tapestry.servlet-container";92}...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:DefaultTestContext.java  
1package org.testng;23import java.util.Collection;4import java.util.Date;567/**8 * This class/interface 9 */10public class DefaultTestContext implements ITestContext {1112  /**13   * @see org.testng.ITestContext#getAllTestMethods()14   */15  public ITestNGMethod[] getAllTestMethods() {16    return null;17  }1819  /**20   * @see org.testng.ITestContext#getEndDate()21   */22  public Date getEndDate() {23    return null;24  }2526  /**27   * @see org.testng.ITestContext#getExcludedGroups()28   */29  public String[] getExcludedGroups() {30    return null;31  }3233  /**34   * @see org.testng.ITestContext#getExcludedMethods()35   */36  public Collection<ITestNGMethod> getExcludedMethods() {37    return null;38  }3940  /**41   * @see org.testng.ITestContext#getFailedButWithinSuccessPercentageTests()42   */43  public IResultMap getFailedButWithinSuccessPercentageTests() {44    return null;45  }4647  /**48   * @see org.testng.ITestContext#getFailedConfigurations()49   */50  public IResultMap getFailedConfigurations() {51    return null;52  }5354  /**55   * @see org.testng.ITestContext#getFailedTests()56   */57  public IResultMap getFailedTests() {58    return null;59  }6061  /**62   * @see org.testng.ITestContext#getHost()63   */64  public String getHost() {65    return null;66  }6768  /**69   * @see org.testng.ITestContext#getIncludedGroups()70   */71  public String[] getIncludedGroups() {72    return null;73  }7475  /**76   * @see org.testng.ITestContext#getName()77   */78  public String getName() {79    return null;80  }8182  /**83   * @see org.testng.ITestContext#getOutputDirectory()84   */85  public String getOutputDirectory() {86    return null;87  }8889  /**90   * @see org.testng.ITestContext#getPassedConfigurations()91   */92  public IResultMap getPassedConfigurations() {93    return null;94  }9596  /**97   * @see org.testng.ITestContext#getPassedTests()98   */99  public IResultMap getPassedTests() {100    return null;101  }102103  /**104   * @see org.testng.ITestContext#getSkippedConfigurations()105   */106  public IResultMap getSkippedConfigurations() {107    return null;108  }109110  /**111   * @see org.testng.ITestContext#getSkippedTests()112   */113  public IResultMap getSkippedTests() {114    return null;115  }116117  /**118   * @see org.testng.ITestContext#getStartDate()119   */120  public Date getStartDate() {121    return null;122  }123124  /**125   * @see org.testng.ITestContext#getSuite()126   */127  public ISuite getSuite() {128    return null;129  }130131}
...Source:ITestBase.java  
1package ftnt.qa.autotest.ui.framework.testbase;23import java.lang.reflect.Method;45import org.testng.ITestContext;6import org.testng.ITestResult;7import org.testng.annotations.AfterClass;8import org.testng.annotations.AfterMethod;9import org.testng.annotations.AfterSuite;10import org.testng.annotations.AfterTest;11import org.testng.annotations.BeforeClass;12import org.testng.annotations.BeforeMethod;13import org.testng.annotations.BeforeSuite;14import org.testng.annotations.BeforeTest;15import org.testng.xml.XmlTest;1617/**18 * @author Lei.Wu19 * æµè¯åºç±»æ¥å£20 */21public interface ITestBase {2223	@BeforeSuite24	public void initTest(XmlTest xt, ITestContext tc) throws Exception;2526	@AfterSuite27	public void terminTestSuite(XmlTest xt, ITestContext tc) throws Exception;2829	@BeforeClass30	public void beforeClass(XmlTest xt, ITestContext tc) throws Exception;3132	@AfterClass33	public void afterClass(XmlTest xt, ITestContext tc) throws Exception;3435//	@BeforeTest36//	public void beforeTest(XmlTest xt, ITestContext tc) throws Exception;37//38//	@AfterTest39//	public void afterTest(XmlTest xt, ITestContext tc) throws Exception;4041	@BeforeMethod42	public void initDriver(ITestContext tc, Method m, XmlTest xt) throws Exception;4344	@AfterMethod45	public void cleanEnv(ITestResult rs, XmlTest xt, Method m, ITestContext tc) throws Exception;
...Source:SearchAndBuyPhone.java  
1package testcasessuiteb;2import org.testng.Assert;3import org.testng.ITestContext;4import org.testng.SkipException;5import org.testng.annotations.Test;6public class SearchAndBuyPhone {7	8	//boolean flag=true; // read - xls,Json9	10	11	boolean flag=false;12	//ITestContext : interface13	14	@Test(priority = 1) // there is no such main function in testNG15	public void search(ITestContext context)  // function is a Test case  there is no main function in TestNg16	{ // failing Skipping17		if(flag)18			19			throw new SkipException("Skipping Test");20		 System.out.println("Searching Phone");21		 //phone name22		 context.setAttribute("phoneName", "Iphone 12");23		 24		 ///how to we transfer test results from one to another25		 26	}// test cases in seperate java file can not be passed as ITestContext  // for this structure just in the same file27	28	@Test(priority = 2, dependsOnMethods = {"search"}) // give the priority for the execution29	public void selectPhone(ITestContext context)30	{31		String name = (String)context.getAttribute("phoneName");32		33		System.out.println("Selecting phone"+name);34		Assert.fail(); // in case any one of these is giving the error35	}36   37	@Test(priority = 3,dependsOnMethods = {"search", "selectPhone"} )38	public void checkout()39	{40		System.out.println("Checking out");41	}42}...Source:Listeners.java  
1package TestNGProject;2import org.testng.ITestContext;3import org.testng.ITestListener;4import org.testng.ITestResult;5//ITestListener interface that implements TestNG listeners6    public class Listeners implements ITestListener {7    @Override8    public void onTestStart(ITestResult iTestResult) {9    }10    @Override11    public void onTestSuccess(ITestResult iTestResult) {12        System.out.println("I've successfully executed Listeners Pass Code");13    }14    @Override15    public void onTestFailure(ITestResult iTestResult) {16        //Screenshot code17        //response if API is failed18        System.out.println("This is my Listener for when their is a Failed Test; the test that was failed is " + iTestResult.getName());19    }20    @Override21    public void onTestSkipped(ITestResult iTestResult) {22    }23    @Override24    public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {25    }26    @Override27    public void onStart(ITestContext iTestContext) {28    }29    @Override30    public void onFinish(ITestContext iTestContext) {31    }32}...Interface ITestContext
Using AI Code Generation
1import org.testng.ITestContext;2import org.testng.ITestListener;3import org.testng.ITestResult;4public class TestNGListener implements ITestListener {5    public void onTestStart(ITestResult result) {6    }7    public void onTestSuccess(ITestResult result) {8    }9    public void onTestFailure(ITestResult result) {10    }11    public void onTestSkipped(ITestResult result) {12    }13    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {14    }15    public void onStart(ITestContext context) {16    }17    public void onFinish(ITestContext context) {18    }19}Interface ITestContext
Using AI Code Generation
1package com.test;2import org.testng.ITestContext;3import org.testng.ITestListener;4import org.testng.ITestResult;5public class TestNGListener implements ITestListener {6    public void onTestStart(ITestResult result) {7        System.out.println("onTestStart method " + result.getName() + " start");8    }9    public void onTestSuccess(ITestResult result) {10        System.out.println("onTestSuccess method " + result.getName() + " succeed");11    }12    public void onTestFailure(ITestResult result) {13        System.out.println("onTestFailure method " + result.getName() + " failed");14    }15    public void onTestSkipped(ITestResult result) {16        System.out.println("onTestSkipped method " + result.getName() + " skipped");17    }18    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {19        System.out.println("onTestFailedButWithinSuccessPercentage " + result.getName());20    }21    public void onStart(ITestContext context) {22        System.out.println("onStart method " + context.getName());23    }24    public void onFinish(ITestContext context) {25        System.out.println("onFinish method " + context.getName());26    }27}28package com.test;29import org.testng.annotations.Listeners;30import org.testng.annotations.Test;31@Listeners(TestNGListener.class)32public class TestNGListenerDemo {33    public void test1() {34        System.out.println("I am inside test1");35    }36    public void test2() {37        System.out.println("I am inside test2");38    }39    public void test3() {40        System.out.println("I am inside test3");41    }42}Interface ITestContext
Using AI Code Generation
1public class TestNGTestContext implements ITestContext {2    public String getName() {3        return null;4    }5    public Object getAttribute(String s) {6        return null;7    }8    public void setAttribute(String s, Object o) {9    }10    public void removeAttribute(String s) {11    }12    public Set<String> getAttributeNames() {13        return null;14    }15    public String getOutputDirectory() {16        return null;17    }18    public IResultMap getPassedTests() {19        return null;20    }21    public IResultMap getFailedTests() {22        return null;23    }24    public IResultMap getSkippedTests() {25        return null;26    }27    public IResultMap getFailedButWithinSuccessPercentageTests() {28        return null;29    }30    public ITestNGMethod[] getAllTestMethods() {31        return new ITestNGMethod[0];32    }33    public Collection<ITestNGMethod> getExcludedMethods() {34        return null;35    }36    public String getHost() {37        return null;38    }39    public Collection<ITestNGMethod> getIncludedMethods() {40        return null;41    }42    public Date getStartDate() {43        return null;44    }45    public Date getEndDate() {46        return null;47    }48    public String getSuiteName() {49        return null;50    }51    public XmlSuite getSuite() {52        return null;53    }54    public String getTestName() {55        return null;56    }57    public XmlTest getCurrentXmlTest() {58        return null;59    }60    public ITestNGMethod getCurrentXmlTestAllParameters() {61        return null;62    }63    public ITestNGMethod getCurrentXmlTestAllParameters(String s) {64        return null;65    }66    public Set<ITestResult> getFailedConfigurations() {67        return null;68    }69    public Set<ITestResult> getPassedConfigurations() {70        return null;Interface ITestContext
Using AI Code Generation
1import org.testng.ITestContext;2import org.testng.ITestListener;3import org.testng.ITestResult;4import org.testng.Reporter;5public class TestNGListener implements ITestListener {6    public void onTestStart(ITestResult Result) {7        System.out.println(Result.getName()+" test case started");8    }9    public void onTestSuccess(ITestResult Result) {10        System.out.println("The name of the testcase passed is :"+Result.getName());11    }12    public void onTestFailure(ITestResult Result) {13        System.out.println("The name of the testcase failed is :"+Result.getName());14    }15    public void onTestSkipped(ITestResult Result) {16        System.out.println("The name of the testcase Skipped is :"+Result.getName());17    }18    public void onTestFailedButWithinSuccessPercentage(ITestResult Result) {19    }20    public void onStart(ITestContext Result) {21        System.out.println(Result.getName()+" test case started");22    }23    public void onFinish(ITestContext Result) {24        System.out.println("Test cases execution is finished");25    }26}27import org.testng.ITestContext;28import org.testng.ITestListener;29import org.testng.ITestResult;30import org.testng.Reporter;31public class TestNGListener implements ITestListener {32    public void onTestStart(ITestResult Result) {33        System.out.println(Result.getName()+" test case started");34    }35    public void onTestSuccess(ITestResult Result) {36        System.out.println("The name of the testcase passed is :"+Result.getName());37    }38    public void onTestFailure(ITestResult Result) {39        System.out.println("The name ofInterface ITestContext
Using AI Code Generation
1public void test(ITestContext context){2    String browser = context.getCurrentXmlTest().getParameter("browser");3    System.out.println(browser);4}5public void test(ITestContext context){6    String browser = context.getCurrentXmlTest().getParameter("browser");7    System.out.println(browser);8}9public void test(ITestContext context){10    String browser = context.getCurrentXmlTest().getParameter("browser");11    System.out.println(browser);12}13public void test(ITestContext context){14    String browser = context.getCurrentXmlTest().getParameter("browser");15    System.out.println(browser);16}17public void test(ITestContext context){18    String browser = context.getCurrentXmlTest().getParameter("browser");19    System.out.println(browser);20}21public void test(ITestContext context){22    String browser = context.getCurrentXmlTest().getParameter("browser");23    System.out.println(browser);24}25public void test(ITestContext context){26    String browser = context.getCurrentXmlTest().getParameter("browser");27    System.out.println(browser);28}29public void test(ITestContext context){30    String browser = context.getCurrentXmlTest().getParameter("browser");31    System.out.println(browser);32}33public void test(ITestContext context){34    String browser = context.getCurrentXmlTest().getParameter("browser");35    System.out.println(browser);Source: Is it possible to put a condition to TestNG to run the test if that is member of two groups? 
1public MyFragment MyFragment(){2        return this;3    }41public enum State {2   abstract State processFoo();3   abstract State processBar();4   State processBat() { return this; } // A default implementation, so that states that do not use this event do not have to implement it anyway.5   ...6   State1 {7     State processFoo() { return State2; }8     ...9   },10   State2 {11      State processFoo() { return State1; }12      ...13   } 14}1516public enum  Event {17   abstract State dispatch(State state);18   Foo {19      State dispatch(State s) { return s.processFoo(); }20   },21   Bar {22      State dispatch(State s) { return s.processBar(); }23   }24   ...25}26TestNG 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!!
