Best Testng code snippet using org.testng.xml.XmlTest.setJunit
Source:GenerateFailedReports.java  
1/**2 * 3 */4package com.gtech.util.listeners;5import org.testng.IReporter;6import org.testng.ISuite;7import org.testng.ISuiteResult;8import org.testng.ITestContext;9import org.testng.ITestNGMethod;10import org.testng.ITestResult;11import org.testng.TestListenerAdapter;12import org.testng.collections.Lists;13import org.testng.collections.Maps;14import org.testng.internal.MethodHelper;15import org.testng.internal.Utils;16import org.testng.internal.annotations.Sets;17import org.testng.xml.XmlClass;18import org.testng.xml.XmlInclude;19import org.testng.xml.XmlSuite;20import org.testng.xml.XmlTest;21import java.util.Collection;22import java.util.HashSet;23import java.util.List;24import java.util.Map;25import java.util.Set;26/**27 * @author bhupesh.b28 *29 */30public class GenerateFailedReports extends TestListenerAdapter implements IReporter {31  public static final String TESTNG_FAILED_XML = "testng-failed.xml";32  private XmlSuite m_xmlSuite;33  public GenerateFailedReports() {34  }35  public GenerateFailedReports(XmlSuite xmlSuite) {36    m_xmlSuite = xmlSuite;37  }38  @Override39  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {40    for(int i= 0; i < suites.size(); i++) {41      generateFailureSuite(suites.get(i).getXmlSuite(), suites.get(i), outputDirectory);42    }43  }44  protected void generateFailureSuite(XmlSuite xmlSuite, ISuite suite, String outputDir) {45    XmlSuite failedSuite = (XmlSuite) xmlSuite.clone();46    failedSuite.setName("Failed suite [" + xmlSuite.getName() + "]");47    m_xmlSuite= failedSuite;48    Map<String, XmlTest> xmlTests= Maps.newHashMap();49    for(XmlTest xmlT: xmlSuite.getTests()) {50      xmlTests.put(xmlT.getName(), xmlT);51    }52    Map<String, ISuiteResult> results = suite.getResults();53    for(Map.Entry<String, ISuiteResult> entry : results.entrySet()) {54      ISuiteResult suiteResult = entry.getValue();55      ITestContext testContext = suiteResult.getTestContext();56      generateXmlTest(suite,57                      xmlTests.get(testContext.getName()),58                      testContext,59                      testContext.getFailedTests().getAllResults(),60                      testContext.getSkippedTests().getAllResults());61    }62    if(null != failedSuite.getTests() && failedSuite.getTests().size() > 0) {63      Utils.writeUtf8File(outputDir, TESTNG_FAILED_XML, failedSuite.toXml());64      Utils.writeUtf8File(suite.getOutputDirectory(), TESTNG_FAILED_XML, failedSuite.toXml());65    }66  }67  /**68   * Do not rely on this method. The class is used as <code>IReporter</code>.69   *70   * @see org.testng.TestListenerAdapter#onFinish(org.testng.ITestContext)71   * @deprecated this class is used now as IReporter72   */73  @Deprecated74  @Override75  public void onFinish(ITestContext context) {76    // Delete the previous file77//    File f = new File(context.getOutputDirectory(), getFileName(context));78//    f.delete();79    // Calculate the methods we need to rerun :  failed tests and80    // their dependents81//    List<ITestResult> failedTests = getFailedTests();82//    List<ITestResult> skippedTests = getSkippedTests();83  }84  @SuppressWarnings({ "unchecked", "deprecation" })85private void generateXmlTest(ISuite suite,86                               XmlTest xmlTest,87                               ITestContext context,88                               Collection<ITestResult> failedTests,89                               Collection<ITestResult> skippedTests) {90    // Note:  we can have skipped tests and no failed tests91    // if a method depends on nonexistent groups92    if (skippedTests.size() > 0 || failedTests.size() > 0) {93      Set<ITestNGMethod> methodsToReRun = Sets.newHashSet();94      // Get the transitive closure of all the failed methods and the methods95      // they depend on96      @SuppressWarnings("rawtypes")97	Collection[] allTests = new Collection[] {98          failedTests, skippedTests99      };100      for (Collection<ITestResult> tests : allTests) {101        for (ITestResult failedTest : tests) {102          ITestNGMethod current = failedTest.getMethod();103          if (current.isTest()) {104            methodsToReRun.add(current);105            ITestNGMethod method = failedTest.getMethod();106            // Don't count configuration methods107            if (method.isTest()) {108              List<ITestNGMethod> methodsDependedUpon =109                  MethodHelper.getMethodsDependedUpon(method, context.getAllTestMethods());110              for (ITestNGMethod m : methodsDependedUpon) {111                if (m.isTest()) {112                  methodsToReRun.add(m);113                }114              }115            }116          }117        }118      }119      //120      // Now we have all the right methods.  Go through the list of121      // all the methods that were run and only pick those that are122      // in the methodToReRun map.  Since the methods are already123      // sorted, we don't need to sort them again.124      //125      List<ITestNGMethod> result = Lists.newArrayList();126      for (ITestNGMethod m : context.getAllTestMethods()) {127        if (methodsToReRun.contains(m)) {128          result.add(m);129        }130      }131      methodsToReRun.clear();132      Collection<ITestNGMethod> invoked= suite.getInvokedMethods();133      for(ITestNGMethod tm: invoked) {134        if(!tm.isTest()) {135          methodsToReRun.add(tm);136        }137      }138      result.addAll(methodsToReRun);139      createXmlTest(context, result, xmlTest);140    }141  }142  /**143   * Generate testng-failed.xml144   */145  private void createXmlTest(ITestContext context, List<ITestNGMethod> methods, XmlTest srcXmlTest) {146    XmlTest xmlTest = new XmlTest(m_xmlSuite);147    xmlTest.setName(context.getName() + "(failed)");148    xmlTest.setBeanShellExpression(srcXmlTest.getExpression());149    xmlTest.setIncludedGroups(srcXmlTest.getIncludedGroups());150    xmlTest.setExcludedGroups(srcXmlTest.getExcludedGroups());151    xmlTest.setParallel(srcXmlTest.getParallel());152    xmlTest.setParameters(srcXmlTest.getLocalParameters());153    xmlTest.setJUnit(srcXmlTest.isJUnit());154    List<XmlClass> xmlClasses = createXmlClasses(methods, srcXmlTest);155    xmlTest.setXmlClasses(xmlClasses);156  }157  /**158   * @param methods The methods we want to represent159   * @param srcXmlTest 160   * @return A list of XmlClass objects (each representing a <class> tag) based161   * on the parameter methods162   */163  @SuppressWarnings({ "rawtypes", "deprecation" })164private List<XmlClass> createXmlClasses(List<ITestNGMethod> methods, XmlTest srcXmlTest) {165    List<XmlClass> result = Lists.newArrayList();166    Map<Class, Set<ITestNGMethod>> methodsMap= Maps.newHashMap();167    for (ITestNGMethod m : methods) {168      Object[] instances= m.getInstances();169      Class clazz= instances == null || instances.length == 0 || instances[0] == null170          ? m.getRealClass()171          : instances[0].getClass();172      Set<ITestNGMethod> methodList= methodsMap.get(clazz);173      if(null == methodList) {174        methodList= new HashSet<ITestNGMethod>();175        methodsMap.put(clazz, methodList);176      }177      methodList.add(m);178    }179    // Ideally, we should preserve each parameter in each class but putting them180    // all in the same bag for now181    Map<String, String> parameters = Maps.newHashMap();182    for (XmlClass c : srcXmlTest.getClasses()) {183      parameters.putAll(c.getLocalParameters());184    }185    int index = 0;186    for(Map.Entry<Class, Set<ITestNGMethod>> entry: methodsMap.entrySet()) {187      Class clazz= entry.getKey();188      Set<ITestNGMethod> methodList= entry.getValue();189      // @author Borojevic190      // Need to check all the methods, not just @Test ones.191      XmlClass xmlClass= new XmlClass(clazz.getName(), index++, false /* don't load classes */);192      List<XmlInclude> methodNames= Lists.newArrayList(methodList.size());193      int ind = 0;194      for(ITestNGMethod m: methodList) {195        methodNames.add(new XmlInclude(m.getMethod().getName(), m.getFailedInvocationNumbers(),196            ind++));197      }198      xmlClass.setIncludedMethods(methodNames);199      xmlClass.setParameters(parameters);200      result.add(xmlClass);201    }202    return result;203  }204  /**205   * TODO:  we might want to make that more flexible in the future, but for206   * now, hardcode the file name207   */208  @SuppressWarnings("unused")209private String getFileName(ITestContext context) {210    return TESTNG_FAILED_XML;211  }212  @SuppressWarnings("unused")213private static void ppp(String s) {214    System.out.println("[GenerateFailedReports] " + s);215  }216}...Source:TestNGRunner.java  
1package de.lemona.android.testng;2import android.app.Instrumentation;3import android.os.Bundle;4import android.os.Debug;5import android.util.Log;6import org.testng.TestNG;7import org.testng.collections.Lists;8import org.testng.xml.Parser;9import org.testng.xml.XmlClass;10import org.testng.xml.XmlSuite;11import org.testng.xml.XmlTest;12import java.io.FileNotFoundException;13import java.io.InputStream;14import java.util.Enumeration;15import java.util.List;16import dalvik.system.DexFile;17import static de.lemona.android.testng.TestNGLogger.TAG;18/**19 * The root of all evil, creating a TestNG {@link XmlSuite} and running it.20 */21public class TestNGRunner extends Instrumentation {22    private String targetPackage = null;23    private TestNGArgs args;24    @Override25    public void onCreate(Bundle arguments) {26        super.onCreate(arguments);27        args = parseRunnerArgument(arguments);28        targetPackage = this.getTargetContext().getPackageName();29        this.start();30    }31    private TestNGArgs parseRunnerArgument(Bundle arguments) {32        Log.d(TAG, "DEBUG arguments");33        for (String key : arguments.keySet()) {34            Log.d(TAG, "key " + key + " = " + arguments.get(key));35        }36        Log.d(TAG, "DEBUG argumetns END");37        TestNGArgs.Builder builder = new TestNGArgs.Builder(this).fromBundle(arguments);38        return builder.build();39    }40    @Override41    public void onStart() {42        final TestNGListener listener = new TestNGListener(this);43        AndroidTestNGSupport.injectInstrumentation(this);44        if (args.debug) {45            // waitForDebugger46            Log.d(TAG, "waiting for debugger...");47            Debug.waitForDebugger();48            Log.d(TAG, "debugger was connected.");49        }50        setupDexmakerClassloader();51        final TestNG ng = new TestNG(false);52        ng.setDefaultSuiteName("Android TestNG Suite");53        ng.setDefaultTestName("Android TestNG Test");54        // Try to load "testng.xml" from the assets directory...55        try {56            final InputStream input = this.getContext().getAssets().open("testng.xml");57            if (input != null) ng.setXmlSuites(new Parser(input).parseToList());58        } catch (final FileNotFoundException exception) {59            Log.d(TAG, "The \"testng.xml\" file was not found in assets");60        } catch (final Throwable throwable) {61            Log.e(TAG, "An unexpected error occurred parsing \"testng.xml\"", throwable);62            listener.fail(this.getClass().getName(), "onStart", throwable);63        }64        try {65            // Our XML suite for running tests66            final XmlSuite xmlSuite = new XmlSuite();67            xmlSuite.setVerbose(0);68            xmlSuite.setJUnit(false);69            xmlSuite.setName(targetPackage);70            // Open up the DEX file associated with our APK71            final String apk = this.getContext().getPackageCodePath();72            final DexFile dex = new DexFile(apk);73            final Enumeration<String> e = dex.entries();74            // Prepare our XML test and list of classes75            final XmlTest xmlTest = new XmlTest(xmlSuite);76            final List<XmlClass> xmlClasses = Lists.newArrayList();77            // Process every element of the DEX file78            while (e.hasMoreElements()) {79                final String cls = e.nextElement();80                if (! cls.startsWith(targetPackage)) continue;81                Log.d(TAG, "Adding potential test class " + cls);82                try {83                    xmlClasses.add(new XmlClass(cls, true));84                } catch (final Throwable throwable) {85                    // Likely NoClassDefException for missing dependencies86                    Log.w(TAG, "Ignoring class " + cls, throwable);87                }88            }89            // Remember our classes if we have to90            if (! xmlClasses.isEmpty()) {91                Log.i(TAG, "Adding suite from package \"" + targetPackage + "\"");92                xmlTest.setXmlClasses(xmlClasses);93                ng.setCommandLineSuite(xmlSuite);94            }95        } catch (final Throwable throwable) {96            Log.e(TAG, "An unexpected error occurred analysing package \"" + targetPackage + "\"", throwable);97            listener.fail(this.getClass().getName(), "onStart", throwable);98        }99        // Run tests!100        try {101            ng.addListener(new TestNGLogger());102            if (args.codeCoverage) {103                ng.addListener(new TestNGCoverageListener(this, args.codeCoveragePath));104            }105            ng.addListener((Object) listener);106            ng.runSuitesLocally();107        } catch (final Throwable throwable) {108            Log.e(TAG, "An unexpected error occurred running tests", throwable);109            listener.fail(this.getClass().getName(), "onStart", throwable);110        } finally {111            // Close our listener112            listener.close();113        }114    }115    private void setupDexmakerClassloader() {116        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();117        // must set the context classloader for apps that use a shared uid, see118        // frameworks/base/core/java/android/app/LoadedApk.java119        ClassLoader newClassLoader = this.getClass().getClassLoader();120        //Log.i(LOG_TAG, String.format("Setting context classloader to '%s', Original: '%s'",121        //        newClassLoader.toString(), originalClassLoader.toString()));122        Thread.currentThread().setContextClassLoader(newClassLoader);123    }124}...Source:SuiteDispatcher.java  
1package org.testng.remote;23import org.testng.ISuite;4import org.testng.ISuiteResult;5import org.testng.ITestListener;6import org.testng.ITestResult;7import org.testng.SuiteRunner;8import org.testng.TestNGException;9import org.testng.collections.Lists;10import org.testng.internal.IConfiguration;11import org.testng.internal.Invoker;12import org.testng.internal.PropertiesFile;13import org.testng.remote.adapter.DefaultMastertAdapter;14import org.testng.remote.adapter.IMasterAdapter;15import org.testng.remote.adapter.RemoteResultListener;16import org.testng.xml.XmlSuite;17import org.testng.xml.XmlTest;1819import java.util.Collection;20import java.util.List;21import java.util.Properties;2223/**24 * Dispatches test suits according to the strategy defined.25 *26 *27 * @author	Guy Korland28 * @date 	April 20, 200729 */30public class SuiteDispatcher31{32	/**33	 * Properties allowed in remote.properties34	 */35	public static final String MASTER_STRATEGY = "testng.master.strategy";36	public static final String VERBOSE = "testng.verbose";37	public static final String MASTER_ADPATER = "testng.master.adpter";3839	/**40	 * Values allowed for STRATEGY41	 */42	public static final String STRATEGY_TEST = "test";43	public static final String STRATEGY_SUITE = "suite";4445	final private int m_verbose;46	final private boolean m_isStrategyTest;4748	final private IMasterAdapter m_masterAdpter;495051	/**52	 * Creates a new suite dispatcher.53	 *54	 * @param propertiesFile55	 * @throws Exception56	 */57	public SuiteDispatcher( String propertiesFile) throws TestNGException58	{59		try60		{61			PropertiesFile file = new PropertiesFile( propertiesFile);62			Properties properties = file.getProperties();6364			m_verbose = Integer.parseInt( properties.getProperty(VERBOSE, "1"));6566			String strategy = properties.getProperty(MASTER_STRATEGY, STRATEGY_SUITE);67			m_isStrategyTest = STRATEGY_TEST.equalsIgnoreCase(strategy);6869			String adapter = properties.getProperty(MASTER_ADPATER);70			if( adapter == null)71			{72				m_masterAdpter = new DefaultMastertAdapter();73			}74			else75			{76				Class clazz = Class.forName(adapter);77				m_masterAdpter = (IMasterAdapter)clazz.newInstance();78			}79			m_masterAdpter.init(properties);80		}81		catch( Exception e)82		{83			throw new TestNGException( "Fail to initialize master mode", e);84		}85	}8687	/**88	 * Dispatch test suites89	 * @param suites90	 * @param outputDir91	 * @param javadocAnnotationFinder92	 * @param jdkAnnotationFinder93	 * @param testListeners94	 * @return suites result95	 */96	public List<ISuite> dispatch(IConfiguration configuration,97	    List<XmlSuite> suites, String outputDir, List<ITestListener> testListeners){98		List<ISuite> result = Lists.newArrayList();99		try100		{101			//102			// Dispatch the suites/tests103			//104105			for (XmlSuite suite : suites) {106				suite.setVerbose(m_verbose);107				SuiteRunner suiteRunner = new SuiteRunner(configuration, suite, outputDir);108				RemoteResultListener listener = new RemoteResultListener( suiteRunner);109				if (m_isStrategyTest) {110					for (XmlTest test : suite.getTests()) {111						XmlSuite tmpSuite = new XmlSuite();112						tmpSuite.setXmlPackages(suite.getXmlPackages());113						tmpSuite.setJUnit(suite.isJUnit());114            tmpSuite.setSkipFailedInvocationCounts(suite.skipFailedInvocationCounts());115						tmpSuite.setName("Temporary suite for " + test.getName());116						tmpSuite.setParallel(suite.getParallel());117						tmpSuite.setParameters(suite.getParameters());118						tmpSuite.setThreadCount(suite.getThreadCount());119            tmpSuite.setDataProviderThreadCount(suite.getDataProviderThreadCount());120						tmpSuite.setVerbose(suite.getVerbose());121						tmpSuite.setObjectFactory(suite.getObjectFactory());122						XmlTest tmpTest = new XmlTest(tmpSuite);123						tmpTest.setBeanShellExpression(test.getExpression());124						tmpTest.setXmlClasses(test.getXmlClasses());125						tmpTest.setExcludedGroups(test.getExcludedGroups());126						tmpTest.setIncludedGroups(test.getIncludedGroups());127						tmpTest.setJUnit(test.isJUnit());128						tmpTest.setMethodSelectors(test.getMethodSelectors());129						tmpTest.setName(test.getName());130						tmpTest.setParallel(test.getParallel());131						tmpTest.setParameters(test.getLocalParameters());132						tmpTest.setVerbose(test.getVerbose());133						tmpTest.setXmlClasses(test.getXmlClasses());134						tmpTest.setXmlPackages(test.getXmlPackages());135136						m_masterAdpter.runSuitesRemotely(tmpSuite, listener);137					}138				}139				else140				{141					m_masterAdpter.runSuitesRemotely(suite, listener);142				}143				result.add(suiteRunner);144			}145146			m_masterAdpter.awaitTermination(100000);147148			//149			// Run test listeners150			//151			for (ISuite suite : result) {152				for (ISuiteResult suiteResult : suite.getResults().values()) {153					Collection<ITestResult> allTests[] = new Collection[] {154							suiteResult.getTestContext().getPassedTests().getAllResults(),155							suiteResult.getTestContext().getFailedTests().getAllResults(),156							suiteResult.getTestContext().getSkippedTests().getAllResults(),157							suiteResult.getTestContext().getFailedButWithinSuccessPercentageTests().getAllResults(),158					};159					for (Collection<ITestResult> all : allTests) {160						for (ITestResult tr : all) {161							Invoker.runTestListeners(tr, testListeners);162						}163					}164				}165			}166		}167		catch( Exception ex)168		{169			//TODO add to logs170			ex.printStackTrace();171		}172		return result;173	}174}
...Source:FailureReporter.java  
1package report;23import org.testng.ISuite;4import org.testng.ISuiteResult;5import org.testng.ITestContext;6import org.testng.ITestNGMethod;7import org.testng.ITestResult;8import org.testng.collections.Lists;9import org.testng.collections.Maps;10import org.testng.collections.Sets;11import org.testng.internal.MethodHelper;12import org.testng.internal.Utils;13import org.testng.xml.XmlClass;14import org.testng.xml.XmlSuite;15import org.testng.xml.XmlTest;1617import java.util.Collection;18import java.util.HashSet;19import java.util.List;20import java.util.Map;21import java.util.Set;2223/**24 * This reporter is responsible for creating ctm-failed.xml25 *26 *27 */2829public class FailureReporter extends CustomReport {30	public static final String CTM_FAILED_XML = "ctm-failed.xml";31	public static final String CTM_OUTPUT_DIR = "./resources/";3233	private XmlSuite m_xmlSuite;3435	public FailureReporter() {36	}3738	public FailureReporter(XmlSuite xmlSuite) {39		m_xmlSuite = xmlSuite;40	}41	42	@Override43	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {44	    for (ISuite suite : suites) {45	    	generateFailureSuite(suite.getXmlSuite(), suite, outputDirectory);46	      }47		48	}4950	protected void generateFailureSuite(XmlSuite xmlSuite, ISuite suite, String outputDir) {51		XmlSuite failedSuite = (XmlSuite) xmlSuite.clone();52		failedSuite.setName(application + "_" + environment + "_" + "Failed_Suite");53		m_xmlSuite= failedSuite;5455		Map<String, XmlTest> xmlTests= Maps.newHashMap();56		for(XmlTest xmlT: xmlSuite.getTests()) {57			xmlTests.put(xmlT.getName(), xmlT);58		}59		Map<String, ISuiteResult> results = suite.getResults();60		for(Map.Entry<String, ISuiteResult> entry : results.entrySet()) {61			ISuiteResult suiteResult = entry.getValue();62			ITestContext testContext = suiteResult.getTestContext();63			generateTestXMLReport(suite,64					xmlTests.get(testContext.getName()),65					testContext,66					testContext.getFailedTests().getAllResults(),67					testContext.getSkippedTests().getAllResults());68		}6970		if(null != failedSuite.getTests() && failedSuite.getTests().size() > 0) {71			Utils.writeUtf8File(CTM_OUTPUT_DIR, CTM_FAILED_XML, failedSuite.toXml());72		}73	}7475	@SuppressWarnings({ "unchecked", "rawtypes" })76	private void generateTestXMLReport(ISuite suite, XmlTest xmlTest, ITestContext context, Collection<ITestResult> failedTests,77			Collection<ITestResult> skippedTests) {78		System.out.println("Total number of failed tests : "+failedTests.size());79		if (skippedTests.size() > 0 || failedTests.size() > 0) {80			Set<ITestNGMethod> methodsToReRun = Sets.newHashSet();81			Collection[] allTests = new Collection[] {82					failedTests, skippedTests83			};84			for (Collection<ITestResult> tests : allTests) {85				for (ITestResult failedTest : tests) {86					ITestNGMethod current = failedTest.getMethod();87					if (current.isTest()) {88						methodsToReRun.add(current);89						ITestNGMethod method = failedTest.getMethod();90						if (method.isTest()) {91							List<ITestNGMethod> methodsDependedUpon =92									MethodHelper.getMethodsDependedUpon(method, context.getAllTestMethods());93							for (ITestNGMethod m : methodsDependedUpon) {94								if (m.isTest()) {95									methodsToReRun.add(m);96								}97							}98						}99					}100				}101			}102			List<ITestNGMethod> result = Lists.newArrayList();103			for (ITestNGMethod m : context.getAllTestMethods()) {104				if (methodsToReRun.contains(m)) {105					result.add(m);106				}107			}108			methodsToReRun.clear();109			createTestReportData(context, result, xmlTest);110		}111	}112113	private void createTestReportData(ITestContext context, List<ITestNGMethod> methods, XmlTest srcXmlTest) {114		XmlTest xmlTest = new XmlTest(m_xmlSuite);115		xmlTest.setName(application + "_" + environment + "_" + "Failed_Test");116		xmlTest.setIncludedGroups(srcXmlTest.getIncludedGroups());117		xmlTest.setExcludedGroups(srcXmlTest.getExcludedGroups());118		xmlTest.setParallel(srcXmlTest.getParallel());119		xmlTest.setParameters(srcXmlTest.getLocalParameters());120		xmlTest.setJUnit(srcXmlTest.isJUnit());121		List<XmlClass> xmlClasses = createClassReport(methods, srcXmlTest);122		xmlTest.setXmlClasses(xmlClasses);123	}124125	126	private List<XmlClass> createClassReport(List<ITestNGMethod> methods, XmlTest srcXmlTest) {127		List<XmlClass> result = Lists.newArrayList();128		Map<Class<?>, Set<ITestNGMethod>> methodsMap= Maps.newHashMap();129130		for (ITestNGMethod m : methods) {131			Object instances= m.getInstance();132			Class<?> clazz= instances == null || instances == null133					? m.getRealClass()134							: instances.getClass();135					Set<ITestNGMethod> methodList= methodsMap.get(clazz);136					if(null == methodList) {137						methodList= new HashSet<ITestNGMethod>();138						methodsMap.put(clazz, methodList);139					}140					methodList.add(m);141		}142		Map<String, String> parameters = Maps.newHashMap();143		for (XmlClass c : srcXmlTest.getClasses()) {144			parameters.putAll(c.getLocalParameters());145		}146		int index = 0;147		for(Map.Entry<Class<?>, Set<ITestNGMethod>> entry: methodsMap.entrySet()) {148			Class<?> clazz= entry.getKey();149			XmlClass xmlClass= new XmlClass(clazz.getName(), index++, false);150			result.add(xmlClass);151		}152		return result;153	}154}
...Source:TestNGSuiteBuilder.java  
1package com.sidhant.automata.core.cli.common;2import com.sidhant.automata.core.cli.config.FmwkConfig;3import com.sidhant.automata.core.logger.MyLogger;4import org.apache.commons.lang3.StringUtils;5import org.testng.xml.XmlClass;6import org.testng.xml.XmlSuite;7import org.testng.xml.XmlTest;8import java.time.LocalDate;9import java.util.*;10public class TestNGSuiteBuilder {11    List<XmlTest> xmlTests = new ArrayList<>();12    private XmlSuite createSuite() {13        XmlSuite newSuite = new XmlSuite();14        newSuite.setJUnit(false);15        newSuite.setThreadCount(1);16        newSuite.setName("This suite file was created at : " + LocalDate.now());17        newSuite.setParallel(XmlSuite.ParallelMode.TESTS);18        newSuite.setVerbose(1);19        newSuite.setPreserveOrder(true);20        Map<String, String> params = new HashMap<>();21        params.put("session-id", Long.toString(System.currentTimeMillis()));22        newSuite.setParameters(params);23        return newSuite;24    }25    public List<XmlSuite> build(Set<String> tests) {26        List<XmlSuite> suites = new ArrayList<>();27        tests.stream()28            .map(this::toXmlTests)29            .forEach(xmlTests::add);30        Collections.shuffle(xmlTests);31        addSuite(suites, xmlTests);32        return suites;33    }34    private XmlTest toXmlTests(String className) {35        XmlTest xmlTest = new XmlTest();36        xmlTest.setJUnit(false);37        xmlTest.setClasses(Collections.singletonList(new XmlClass(className)));38        String name = StringUtils.substringAfterLast(className, ".");39        xmlTest.setName(name);40        xmlTest.addParameter("firm", FmwkConfig.getInstance().getFirm());41        return xmlTest;42    }43    private void addSuite(List<XmlSuite> xmlSuites, List<XmlTest> tests) {44        XmlSuite suite = createSuite();45        tests.forEach(test -> {46            test.setSuite(suite);47            suite.addTest(test);48        });49        xmlSuites.add(suite);50        MyLogger.log(suite.toXml(), "SuiteBuilder");51    }52}...setJunit
Using AI Code Generation
1package testng;2import org.testng.annotations.Test;3import org.testng.xml.XmlTest;4public class SetJunit {5    public void setJunitTest(){6        XmlTest test = new XmlTest();7        test.setJunit(true);8    }9}setJunit
Using AI Code Generation
1public class TestNGTest {2    public void test() {3        XmlTest xmlTest = new XmlTest();4        xmlTest.setJunit(true);5        System.out.println(xmlTest.toXml());6    }7}8package com.javacodegeeks.testng;9import org.testng.TestNG;10public class TestNGTest {11    public static void main(String[] args) {12        TestNG testNG = new TestNG();13        testNG.setJUnit(true);14        System.out.println(testNG.toXml());15    }16}17package com.javacodegeeks.testng;18import org.testng.TestNG;19public class TestNGTest {20    public static void main(String[] args) {21        TestNG testNG = new TestNG();22        testNG.setJUnit(true);23        testNG.setTestSuites(Arrays.asList("testng.xml"));24        testNG.run();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!!
