Best Testng code snippet using org.testng.TestNG.getExecutorFactory
Source:TestNG.java
...693 }694 public void setExecutorFactory(IExecutorFactory factory) {695 this.m_executorFactory = factory;696 }697 public IExecutorFactory getExecutorFactory() {698 if (this.m_executorFactory == null) {699 this.m_executorFactory = createExecutorFactoryInstanceUsing(DEFAULT_THREADPOOL_FACTORY);700 }701 return this.m_executorFactory;702 }703 private void initializeCommandLineSuites() {704 if (m_commandLineTestClasses != null || m_commandLineMethods != null) {705 if (null != m_commandLineMethods) {706 m_cmdlineSuites = createCommandLineSuitesForMethods(m_commandLineMethods);707 } else {708 m_cmdlineSuites = createCommandLineSuitesForClasses(m_commandLineTestClasses);709 }710 for (XmlSuite s : m_cmdlineSuites) {711 for (XmlTest t : s.getTests()) {712 t.setPreserveOrder(m_preserveOrder);713 }714 m_suites.add(s);715 if (m_groupByInstances != null) {716 s.setGroupByInstances(m_groupByInstances);717 }718 }719 }720 }721 private void initializeCommandLineSuitesParams() {722 if (null == m_cmdlineSuites) {723 return;724 }725 for (XmlSuite s : m_cmdlineSuites) {726 if (m_threadCount != -1) {727 s.setThreadCount(m_threadCount);728 }729 if (m_parallelMode != null) {730 s.setParallel(m_parallelMode);731 }732 if (m_configFailurePolicy != null) {733 s.setConfigFailurePolicy(m_configFailurePolicy);734 }735 }736 }737 private void initializeCommandLineSuitesGroups() {738 // If groups were specified on the command line, they should override groups739 // specified in the XML file740 boolean hasIncludedGroups = null != m_includedGroups && m_includedGroups.length > 0;741 boolean hasExcludedGroups = null != m_excludedGroups && m_excludedGroups.length > 0;742 List<XmlSuite> suites = m_cmdlineSuites != null ? m_cmdlineSuites : m_suites;743 if (hasIncludedGroups || hasExcludedGroups) {744 for (XmlSuite s : suites) {745 initializeCommandLineSuitesGroups(746 s, hasIncludedGroups, m_includedGroups, hasExcludedGroups, m_excludedGroups);747 }748 }749 }750 private static void initializeCommandLineSuitesGroups(751 XmlSuite s,752 boolean hasIncludedGroups,753 String[] m_includedGroups,754 boolean hasExcludedGroups,755 String[] m_excludedGroups) {756 if (hasIncludedGroups) {757 s.setIncludedGroups(Arrays.asList(m_includedGroups));758 }759 if (hasExcludedGroups) {760 s.setExcludedGroups(Arrays.asList(m_excludedGroups));761 }762 for (XmlSuite child : s.getChildSuites()) {763 initializeCommandLineSuitesGroups(764 child, hasIncludedGroups, m_includedGroups, hasExcludedGroups, m_excludedGroups);765 }766 }767 private void addReporter(Class<? extends IReporter> r) {768 if (!m_reporters.containsKey(r)) {769 m_reporters.put(r, InstanceCreator.newInstance(r));770 }771 }772 private void initializeDefaultListeners() {773 if (m_failIfAllTestsSkipped) {774 this.exitCodeListener.failIfAllTestsSkipped();775 }776 addListener(this.exitCodeListener);777 if (m_useDefaultListeners) {778 addReporter(SuiteHTMLReporter.class);779 addReporter(Main.class);780 addReporter(FailedReporter.class);781 addReporter(XMLReporter.class);782 if (RuntimeBehavior.useOldTestNGEmailableReporter()) {783 addReporter(EmailableReporter.class);784 } else if (RuntimeBehavior.useEmailableReporter()) {785 addReporter(EmailableReporter2.class);786 }787 addReporter(JUnitReportReporter.class);788 if (m_verbose != null && m_verbose > 4) {789 addListener(new VerboseReporter("[TestNG] "));790 }791 }792 }793 private void initializeConfiguration() {794 ITestObjectFactory factory = m_objectFactory;795 //796 // Install the listeners found in ServiceLoader (or use the class797 // loader for tests, if specified).798 //799 addServiceLoaderListeners();800 //801 // Install the listeners found in the suites802 //803 for (XmlSuite s : m_suites) {804 addListeners(s);805 //806 // Install the method selectors807 //808 for (XmlMethodSelector methodSelector : s.getMethodSelectors()) {809 addMethodSelector(methodSelector.getClassName(), methodSelector.getPriority());810 addMethodSelector(methodSelector);811 }812 //813 // Find if we have an object factory814 //815 if (s.getObjectFactory() != null) {816 if (factory == null) {817 factory = s.getObjectFactory();818 } else {819 throw new TestNGException("Found more than one object-factory tag in your suites");820 }821 }822 }823 m_configuration.setAnnotationFinder(new JDK15AnnotationFinder(getAnnotationTransformer()));824 m_configuration.setHookable(m_hookable);825 m_configuration.setConfigurable(m_configurable);826 m_configuration.setObjectFactory(factory);827 m_configuration.setAlwaysRunListeners(this.m_alwaysRun);828 m_configuration.setExecutorFactory(getExecutorFactory());829 }830 private void addListeners(XmlSuite s) {831 for (String listenerName : s.getListeners()) {832 Class<?> listenerClass = ClassHelper.forName(listenerName);833 // If specified listener does not exist, a TestNGException will be thrown834 if (listenerClass == null) {835 throw new TestNGException(836 "Listener " + listenerName + " was not found in project's classpath");837 }838 ITestNGListener listener = (ITestNGListener) InstanceCreator.newInstance(listenerClass);839 addListener(listener);840 }841 // Add the child suite listeners842 List<XmlSuite> childSuites = s.getChildSuites();843 for (XmlSuite c : childSuites) {844 addListeners(c);845 }846 }847 /** Using reflection to remain Java 5 compliant. */848 private void addServiceLoaderListeners() {849 Iterable<ITestNGListener> loader =850 m_serviceLoaderClassLoader != null851 ? ServiceLoader.load(ITestNGListener.class, m_serviceLoaderClassLoader)852 : ServiceLoader.load(ITestNGListener.class);853 for (ITestNGListener l : loader) {854 Utils.log("[TestNG]", 2, "Adding ServiceLoader listener:" + l);855 if (m_listenersToSkipFromBeingWiredIn.contains(l.getClass().getName())) {856 Utils.log("[TestNG]", 2, "Skipping adding the listener :" + l);857 continue;858 }859 addListener(l);860 addServiceLoaderListener(l);861 }862 }863 /**864 * Before suites are executed, do a sanity check to ensure all required conditions are met. If865 * not, throw an exception to stop test execution866 *867 * @throws TestNGException if the sanity check fails868 */869 private void sanityCheck() {870 XmlSuiteUtils.validateIfSuitesContainDuplicateTests(m_suites);871 XmlSuiteUtils.adjustSuiteNamesToEnsureUniqueness(m_suites);872 }873 /** Invoked by the remote runner. */874 public void initializeEverything() {875 // The Eclipse plug-in (RemoteTestNG) might have invoked this method already876 // so don't initialize suites twice.877 if (m_isInitialized) {878 return;879 }880 initializeSuitesAndJarFile();881 initializeConfiguration();882 initializeDefaultListeners();883 initializeCommandLineSuites();884 initializeCommandLineSuitesParams();885 initializeCommandLineSuitesGroups();886 m_isInitialized = true;887 }888 /** Run TestNG. */889 public void run() {890 initializeEverything();891 sanityCheck();892 runExecutionListeners(true /* start */);893 runSuiteAlterationListeners();894 m_start = System.currentTimeMillis();895 List<ISuite> suiteRunners = runSuites();896 m_end = System.currentTimeMillis();897 if (null != suiteRunners) {898 generateReports(suiteRunners);899 }900 runExecutionListeners(false /* finish */);901 exitCode = this.exitCodeListener.getStatus();902 if (exitCodeListener.noTestsFound()) {903 if (TestRunner.getVerbose() > 1) {904 System.err.println("[TestNG] No tests found. Nothing was run");905 usage();906 }907 }908 m_instance = null;909 m_jCommander = null;910 }911 /**912 * Run the test suites.913 *914 * <p>This method can be overridden by subclass. <br>915 * For example, DistributedTestNG to run in master/slave mode according to commandline args.916 *917 * @return - List of suites that were run as {@link ISuite} objects.918 * @since 6.9.11 when moving distributed/remote classes out into separate project919 */920 protected List<ISuite> runSuites() {921 return runSuitesLocally();922 }923 private void runSuiteAlterationListeners() {924 for (IAlterSuiteListener l : m_alterSuiteListeners.values()) {925 l.alter(m_suites);926 }927 }928 private void runExecutionListeners(boolean start) {929 for (IExecutionListener l : m_configuration.getExecutionListeners()) {930 if (start) {931 l.onExecutionStart();932 } else {933 l.onExecutionFinish();934 }935 }936 }937 private static void usage() {938 if (m_jCommander == null) {939 m_jCommander = new JCommander(new CommandLineArgs());940 }941 m_jCommander.usage();942 }943 private void generateReports(List<ISuite> suiteRunners) {944 for (IReporter reporter : m_reporters.values()) {945 try {946 long start = System.currentTimeMillis();947 reporter.generateReport(m_suites, suiteRunners, m_outputDir);948 Utils.log(949 "TestNG",950 2,951 "Time taken by " + reporter + ": " + (System.currentTimeMillis() - start) + " ms");952 } catch (Exception ex) {953 System.err.println("[TestNG] Reporter " + reporter + " failed");954 ex.printStackTrace(System.err);955 }956 }957 }958 /**959 * This needs to be public for maven2, for now..At least until an alternative mechanism is found.960 * @return The locally run suites961 */962 public List<ISuite> runSuitesLocally() {963 if (m_suites.isEmpty()) {964 error("No test suite found. Nothing to run");965 usage();966 return Collections.emptyList();967 }968 SuiteRunnerMap suiteRunnerMap = new SuiteRunnerMap();969 // First initialize the suite runners to ensure there are no configuration issues.970 // Create a map with XmlSuite as key and corresponding SuiteRunner as value971 for (XmlSuite xmlSuite : m_suites) {972 createSuiteRunners(suiteRunnerMap, xmlSuite);973 }974 //975 // Run suites976 //977 if (m_suiteThreadPoolSize == 1 && !m_randomizeSuites) {978 // Single threaded and not randomized: run the suites in order979 for (XmlSuite xmlSuite : m_suites) {980 runSuitesSequentially(981 xmlSuite, suiteRunnerMap, getVerbose(xmlSuite), getDefaultSuiteName());982 }983 //984 // Generate the suites report985 //986 return Lists.newArrayList(suiteRunnerMap.values());987 }988 // Multithreaded: generate a dynamic graph that stores the suite hierarchy. This is then989 // used to run related suites in specific order. Parent suites are run only990 // once all the child suites have completed execution991 IDynamicGraph<ISuite> suiteGraph = new DynamicGraph<>();992 for (XmlSuite xmlSuite : m_suites) {993 populateSuiteGraph(suiteGraph, suiteRunnerMap, xmlSuite);994 }995 IThreadWorkerFactory<ISuite> factory =996 new SuiteWorkerFactory(997 suiteRunnerMap, 0 /* verbose hasn't been set yet */, getDefaultSuiteName());998 ITestNGThreadPoolExecutor pooledExecutor = this.getExecutorFactory().newSuiteExecutor(999 "suites",1000 suiteGraph,1001 factory,1002 m_suiteThreadPoolSize,1003 m_suiteThreadPoolSize,1004 Integer.MAX_VALUE,1005 TimeUnit.MILLISECONDS,1006 new LinkedBlockingQueue<>(),1007 null);1008 Utils.log("TestNG", 2, "Starting executor for all suites");1009 // Run all suites in parallel1010 pooledExecutor.run();1011 try {1012 pooledExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);...
Source:TestRunner.java
...643 if (graph.getNodeCount() <= 0) {644 return;645 }646 ITestNGThreadPoolExecutor executor =647 this.m_configuration.getExecutorFactory().newTestMethodExecutor(648 "test=" + xmlTest.getName(),649 graph,650 this,651 threadCount,652 threadCount,653 0,654 TimeUnit.MILLISECONDS,655 newQueue(needPrioritySort),656 methodComparator);657 executor.run();658 try {659 long timeOut = m_xmlTest.getTimeOut(XmlTest.DEFAULT_TIMEOUT_MS);660 Utils.log(661 "TestRunner",...
Source:TypesafeConfigurationTest.java
...51 CaffeineConfiguration<Integer, Integer> defaults =52 TypesafeConfigurator.defaults(ConfigFactory.load());53 assertThat(defaults.getKeyType(), is(Object.class));54 assertThat(defaults.getValueType(), is(Object.class));55 assertThat(defaults.getExecutorFactory().create(), is(ForkJoinPool.commonPool()));56 assertThat(defaults.getMaximumSize(), is(OptionalLong.of(500)));57 }58 @Test59 public void testCache() {60 Optional<CaffeineConfiguration<Integer, Integer>> config =61 TypesafeConfigurator.from(ConfigFactory.load(), "test-cache");62 assertThat(config.get(), is(equalTo(TypesafeConfigurator.from(63 ConfigFactory.load(), "test-cache").get())));64 checkTestCache(config.get());65 }66 @Test67 public void testCache2() {68 Optional<CaffeineConfiguration<Integer, Integer>> config1 =69 TypesafeConfigurator.from(ConfigFactory.load(), "test-cache");70 Optional<CaffeineConfiguration<Integer, Integer>> config2 =71 TypesafeConfigurator.from(ConfigFactory.load(), "test-cache-2");72 assertThat(config1, is(not(equalTo(config2))));73 assertThat(config2.get().getKeyType(), is(String.class));74 assertThat(config2.get().getValueType(), is(Integer.class));75 assertThat(config2.get().isNativeStatisticsEnabled(), is(false));76 assertThat(config2.get().getExecutorFactory().create(), is(ForkJoinPool.commonPool()));77 }78 @Test79 public void getCache() {80 Cache<Integer, Integer> cache = Caching.getCachingProvider()81 .getCacheManager().getCache("test-cache");82 assertThat(cache, is(not(nullValue())));83 @SuppressWarnings("unchecked")84 CaffeineConfiguration<Integer, Integer> config =85 cache.getConfiguration(CaffeineConfiguration.class);86 checkTestCache(config);87 }88 static void checkTestCache(CaffeineConfiguration<?, ?> config) {89 checkStoreByValue(config);90 checkListener(config);91 assertThat(config.getKeyType(), is(Object.class));92 assertThat(config.getValueType(), is(Object.class));93 assertThat(config.getExecutorFactory().create(), is(instanceOf(TestExecutor.class)));94 assertThat(config.getSchedulerFactory().create(), is(instanceOf(TestScheduler.class)));95 assertThat(config.getCacheLoaderFactory().create(), is(instanceOf(TestCacheLoader.class)));96 assertThat(config.getCacheWriter(), is(instanceOf(TestCacheWriter.class)));97 assertThat(config.isNativeStatisticsEnabled(), is(true));98 assertThat(config.isStatisticsEnabled(), is(true));99 assertThat(config.isManagementEnabled(), is(true));100 checkSize(config);101 checkRefresh(config);102 checkLazyExpiration(config);103 checkEagerExpiration(config);104 }105 static void checkStoreByValue(CaffeineConfiguration<?, ?> config) {106 assertThat(config.isStoreByValue(), is(true));107 assertThat(config.getCopierFactory().create(),...
Source:Configuration.java
...92 public void setExecutorFactory(IExecutorFactory factory) {93 this.m_executorFactory = factory;94 }95 @Override96 public IExecutorFactory getExecutorFactory() {97 return this.m_executorFactory;98 }99 @Override100 public boolean alwaysRunListeners() {101 return alwaysRunListeners;102 }103 @Override104 public void setInjectorFactory(IInjectorFactory factory) {105 this.injectorFactory = factory;106 }107 @Override108 public IInjectorFactory getInjectorFactory() {109 return this.injectorFactory;110 }...
Source:IConfiguration.java
...21 void addConfigurationListener(IConfigurationListener cl);22 boolean alwaysRunListeners();23 void setAlwaysRunListeners(boolean alwaysRun);24 void setExecutorFactory(IExecutorFactory factory);25 IExecutorFactory getExecutorFactory();26 IInjectorFactory getInjectorFactory();27 void setInjectorFactory(IInjectorFactory factory);28}...
getExecutorFactory
Using AI Code Generation
1public class TestNGExecutorFactory implements IExecutorFactory {2 public ITestExecutor newExecutor(ISuite suite) {3 return new TestNGExecutor();4 }5}6public class TestNGExecutor implements ITestExecutor {7 public void run() {8 TestNG testNG = new TestNG();9 testNG.setTestSuites(Arrays.asList("path_to_testng.xml"));10 testNG.run();11 }12}13public class TestNGExecutorFactory implements IExecutorFactory {14 public ITestExecutor newExecutor(ISuite suite) {15 return new TestNGExecutor();16 }17}18public class TestNGExecutor implements ITestExecutor {19 public void run() {20 TestNG testNG = new TestNG();21 testNG.setTestSuites(Arrays.asList("path_to_testng.xml"));22 testNG.run();23 }24}25public class TestNGExecutorFactory implements IExecutorFactory {26 public ITestExecutor newExecutor(ISuite suite) {27 return new TestNGExecutor();28 }29}30public class TestNGExecutor implements ITestExecutor {31 public void run() {32 TestNG testNG = new TestNG();33 testNG.setTestSuites(Arrays.asList("path_to_testng.xml"));34 testNG.run();35 }36}37public class TestNGExecutorFactory implements IExecutorFactory {38 public ITestExecutor newExecutor(ISuite suite) {39 return new TestNGExecutor();40 }41}42public class TestNGExecutor implements ITestExecutor {43 public void run() {44 TestNG testNG = new TestNG();45 testNG.setTestSuites(Arrays.asList("path_to_testng.xml"));46 testNG.run();47 }48}49public class TestNGExecutorFactory implements IExecutorFactory {50 public ITestExecutor newExecutor(ISuite suite) {51 return new TestNGExecutor();52 }53}54public class TestNGExecutor implements ITestExecutor {55 public void run() {56 TestNG testNG = new TestNG();
getExecutorFactory
Using AI Code Generation
1package com.test;2import org.testng.annotations.Test;3import org.testng.TestNG;4import org.testng.ITestNGMethod;5import org.testng.ITestResult;6import org.testng.ITestListener;7import org.testng.ITestContext;8public class TestNGTest {9 public void test() {10 TestNG testNG = new TestNG();11 testNG.setTestClasses(new Class[]{ com.test.TestClass.class });12 testNG.addListener(new ITestListener() {13 public void onTestStart(ITestResult result) {14 System.out.println("onTestStart");15 }16 public void onTestSuccess(ITestResult result) {17 System.out.println("onTestSuccess");18 }19 public void onTestFailure(ITestResult result) {20 System.out.println("onTestFailure");21 }22 public void onTestSkipped(ITestResult result) {23 System.out.println("onTestSkipped");24 }25 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {26 System.out.println("onTestFailedButWithinSuccessPercentage");27 }28 public void onStart(ITestContext context) {29 System.out.println("onStart");30 }31 public void onFinish(ITestContext context) {32 System.out.println("onFinish");33 }34 });35 testNG.run();36 }37}38package com.test;39import org.testng.annotations.Test;40public class TestClass {41 public void test() {42 System.out.println("test");43 }44}45public interface ITestNGListener extends ITestListener {46 void onTestStart(ITestResult result);47 void onTestSuccess(ITestResult result);48 void onTestFailure(ITestResult result);49 void onTestSkipped(ITestResult result);50 void onTestFailedButWithinSuccessPercentage(ITestResult result);51 void onStart(ITestContext context);
getExecutorFactory
Using AI Code Generation
1org.testng.TestNG testNG = new org.testng.TestNG();2testNG.getExecutorFactory();3org.testng.TestNG testNG = new org.testng.TestNG();4testNG.getMethodInterceptor();5org.testng.TestNG testNG = new org.testng.TestNG();6org.testng.IMethodSelector methodSelector = testNG.getMethodSelector();7org.testng.TestNG testNG = new org.testng.TestNG();8org.testng.IMethodValidator methodValidator = testNG.getMethodValidator();9org.testng.TestNG testNG = new org.testng.TestNG();10testNG.getParallelism();11org.testng.TestNG testNG = new org.testng.TestNG();12testNG.getSuiteRunnerFactory();13org.testng.TestNG testNG = new org.testng.TestNG();14testNG.getTestRunnerFactory();15org.testng.TestNG testNG = new org.testng.TestNG();16testNG.getXmlClasses();17org.testng.TestNG testNG = new org.testng.TestNG();18testNG.getXmlPackages();
getExecutorFactory
Using AI Code Generation
1package org.testng;2import org.testng.xml.XmlSuite;3import java.util.ArrayList;4import java.util.Collection;5import java.util.List;6public class TestNG {7 public static void main(String[] args) {8 TestNG testNG = new TestNG();9 testNG.setTestClasses(new Class[]{Test.class});10 testNG.addListener(new TestListenerAdapter());11 testNG.run();12 }13 private Collection<Class> testClasses;14 public void setTestClasses(Class[] testClasses) {15 this.testClasses = new ArrayList<Class>();16 for (Class testClass : testClasses) {17 this.testClasses.add(testClass);18 }19 }20 public void addListener(ITestListener listener) {21 getTestRunner().addListener(listener);22 }23 public void run() {24 getTestRunner().run();25 }26 private ITestRunner getTestRunner() {27 return getExecutor().getTestRunner();28 }29 private ITestNGMethodRunnerFactory getMethodRunnerFactory() {30 return getExecutorFactory().getMethodRunnerFactory();31 }32 private IExecutorFactory getExecutorFactory() {33 return new DefaultExecutorFactory();34 }35 private IExecutor getExecutor() {36 return getExecutorFactory().getExecutor(getConfig(), getMethodRunnerFactory());37 }38 private IConfiguration getConfig() {39 return new Configuration(getXmlSuites(), getTestClasses());40 }41 private Collection<Class> getTestClasses() {42 return testClasses;43 }44 private List<XmlSuite> getXmlSuites() {45 return new ArrayList<XmlSuite>();46 }47}48package org.testng;49public class Test {50 public void test() {51 System.out.println("test");52 }53}54package org.testng;55public class TestListenerAdapter implements ITestListener {56 public void onTestStart(ITestResult result) {57 System.out.println("onTestStart");58 }59 public void onTestSuccess(ITestResult result) {60 System.out.println("onTestSuccess");
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!!