Best Testng code snippet using org.testng.TestNG.getConfiguration
Source:TestNGRunnableState.java
...81 return TESTNG_TEST_FRAMEWORK_NAME;82 }83 @Override84 protected boolean configureByModule(Module module) {85 return module != null && getConfiguration().getPersistantData().getScope() != TestSearchScope.WHOLE_PROJECT;86 }87 @Override88 protected void configureRTClasspath(JavaParameters javaParameters) {89 javaParameters.getClassPath().add(PathUtil.getJarPathForClass(RemoteTestNGStarter.class));90 javaParameters.getClassPath().addTail(PathUtil.getJarPathForClass(JCommander.class));91 }92 @Override93 protected JavaParameters createJavaParameters() throws ExecutionException {94 final JavaParameters javaParameters = super.createJavaParameters();95 javaParameters.setMainClass("org.testng.RemoteTestNGStarter");96 try {97 port = NetUtils.findAvailableSocketPort();98 }99 catch (IOException e) {100 throw new ExecutionException("Unable to bind to port " + port, e);101 }102 final TestData data = getConfiguration().getPersistantData();103 if (data.getOutputDirectory() != null && !data.getOutputDirectory().isEmpty()) {104 javaParameters.getProgramParametersList().add(CommandLineArgs.OUTPUT_DIRECTORY, data.getOutputDirectory());105 }106 javaParameters.getProgramParametersList().add(CommandLineArgs.USE_DEFAULT_LISTENERS, String.valueOf(data.USE_DEFAULT_REPORTERS));107 @NonNls final StringBuilder buf = new StringBuilder();108 if (data.TEST_LISTENERS != null && !data.TEST_LISTENERS.isEmpty()) {109 buf.append(StringUtil.join(data.TEST_LISTENERS, ";"));110 }111 collectListeners(javaParameters, buf, IDEATestNGListener.EP_NAME, ";");112 if (buf.length() > 0) javaParameters.getProgramParametersList().add(CommandLineArgs.LISTENER, buf.toString());113 createServerSocket(javaParameters);114 createTempFiles(javaParameters);115 return javaParameters;116 }117 @Override118 protected List<String> getNamedParams(String parameters) {119 try {120 Integer.parseInt(parameters);121 return super.getNamedParams(parameters);122 }123 catch (NumberFormatException e) {124 return Arrays.asList(parameters.split(" "));125 }126 }127 @NotNull128 @Override129 protected String getForkMode() {130 return "none";131 }132 public SearchingForTestsTask createSearchingForTestsTask() {133 return new SearchingForTestsTask(myServerSocket, config, myTempFile) {134 @Override135 protected void onFound() {136 super.onFound();137 writeClassesPerModule(myClasses);138 }139 };140 }141 protected void writeClassesPerModule(Map<PsiClass, Map<PsiMethod, List<String>>> classes) {142 if (forkPerModule()) {143 final Map<Module, List<String>> perModule = new TreeMap<>((o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true));144 for (final PsiClass psiClass : classes.keySet()) {145 final Module module = ModuleUtilCore.findModuleForPsiElement(psiClass);146 if (module != null) {147 List<String> list = perModule.get(module);148 if (list == null) {149 list = new ArrayList<>();150 perModule.put(module, list);151 }152 list.add(psiClass.getQualifiedName());153 }154 }155 try {156 writeClassesPerModule(getConfiguration().getPackage(), getJavaParameters(), perModule);157 }158 catch (Exception e) {159 LOG.error(e);160 }161 }162 }163 @NotNull164 protected String getFrameworkId() {165 return "testng";166 }167 protected void passTempFile(ParametersList parametersList, String tempFilePath) {168 parametersList.add("-temp", tempFilePath);169 }170 @NotNull171 public TestNGConfiguration getConfiguration() {172 return config;173 }174 @Override175 protected TestSearchScope getScope() {176 return getConfiguration().getPersistantData().getScope();177 }178 protected void passForkMode(String forkMode, File tempFile, JavaParameters parameters) throws ExecutionException {179 final ParametersList parametersList = parameters.getProgramParametersList();180 final List<String> params = parametersList.getParameters();181 int paramIdx = params.size() - 1;182 for (int i = 0; i < params.size(); i++) {183 String param = params.get(i);184 if ("-temp".equals(param)) {185 paramIdx = i;186 break;187 }188 }189 parametersList.addAt(paramIdx, "@@@" + tempFile.getAbsolutePath());190 if (getForkSocket() != null) {...
Source:LauncherTest.java
...40 @Test41 public void testParseAgentIdOk() throws Exception {42 Launcher launcher = new Launcher();43 launcher.parseArgs("-a", "id1");44 assertEquals(launcher.getConfiguration().get(AGENT_ID), "id1");45 launcher.parseArgs(AGENT_ID.concat("=id2"));46 assertEquals(launcher.getConfiguration().get(AGENT_ID), "id2");47 launcher.parseArgs("-c", m_testProperties);48 assertEquals(launcher.getConfiguration().get(AGENT_ID), "myAgentID");49 // -a supersedes agent.identification.agentid!50 launcher.parseArgs("-a", "id1", AGENT_ID.concat("=id2"));51 assertEquals(launcher.getConfiguration().get(AGENT_ID), "id1");52 // command line version supersedes the value in config file!53 launcher.parseArgs("-c", m_testProperties, AGENT_ID.concat("=id2"));54 assertEquals(launcher.getConfiguration().get(AGENT_ID), "id2");55 }56 @Test57 public void testParseServerURLsOk() throws Exception {58 Launcher launcher = new Launcher();59 launcher.parseArgs("-s", "a,b,c");60 assertEquals(launcher.getConfiguration().get(AGENT_DISCOVERY_SERVERURLS), "a,b,c");61 launcher.parseArgs(AGENT_DISCOVERY_SERVERURLS.concat("=d,e,f"));62 assertEquals(launcher.getConfiguration().get(AGENT_DISCOVERY_SERVERURLS), "d,e,f");63 launcher.parseArgs("-c", m_testProperties);64 assertEquals(launcher.getConfiguration().get(AGENT_DISCOVERY_SERVERURLS), "http://localhost:1234/");65 // -s supersedes agent.discovery.serverurls!66 launcher.parseArgs("-s", "a,b,c", AGENT_DISCOVERY_SERVERURLS.concat("=d,e,f"));67 assertEquals(launcher.getConfiguration().get(AGENT_DISCOVERY_SERVERURLS), "a,b,c");68 // command line version supersedes the value in config file!69 launcher.parseArgs("-c", m_testProperties, AGENT_DISCOVERY_SERVERURLS.concat("=d,e,f"));70 assertEquals(launcher.getConfiguration().get(AGENT_DISCOVERY_SERVERURLS), "d,e,f");71 }72 @Test73 public void testParseSystemPropertyOk() throws Exception {74 Launcher launcher = new Launcher();75 launcher.parseArgs("system.property=value", "-c", m_testProperties);76 // The system properties shouldn't be included in the configuration...77 assertNull(launcher.getConfiguration().get("property"));78 assertNull(launcher.getConfiguration().get("prop2"));79 // System properties never are accessible by their full name...80 assertNull(launcher.getProperty("system.property"));81 assertNull(launcher.getProperty("system.prop2"));82 // System properties are only accessible through their stripped name...83 assertEquals(launcher.getProperty("prop2"), "value2");84 assertEquals(launcher.getProperty("property"), "value");85 }86}...
Source:IsolationLevelNoneTest.java
...40 public void testWithoutTransactions() throws Exception41 {42 UnitTestCacheFactory<String, String> instance = new UnitTestCacheFactory<String, String>();43 cache = (CacheSPI<String, String>) instance.createCache(false, getClass());44 cache.getConfiguration().setNodeLockingScheme(Configuration.NodeLockingScheme.PESSIMISTIC);45 cache.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);46 cache.getConfiguration().setIsolationLevel(IsolationLevel.NONE);47 cache.start();48 cache.put(FQN, KEY, VALUE);49 cache.put(FQN + "/d", KEY, VALUE);50 Node node = cache.peek(FQN, false, false);51 assertTrue(node != null && node.getKeys().contains(KEY));52 assertEquals(VALUE, cache.get(FQN, KEY));53 assertEquals(0, cache.getNumberOfLocksHeld());54 }55 public void testWithTransactions() throws Exception56 {57 UnitTestCacheFactory<String, String> instance = new UnitTestCacheFactory<String, String>();58 cache = (CacheSPI<String, String>) instance.createCache(false, getClass());59 cache.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);60 cache.getConfiguration().setNodeLockingScheme(Configuration.NodeLockingScheme.PESSIMISTIC);61 cache.getConfiguration().setIsolationLevel(IsolationLevel.NONE);62 cache.getConfiguration().setTransactionManagerLookupClass(TransactionSetup.getManagerLookup());63 cache.start();64 tm = startTransaction();65 cache.put(FQN, KEY, VALUE);66 cache.put(FQN + "/d", KEY, VALUE);67 Node node = cache.peek(FQN, false, false);68 assertTrue(node != null && node.getKeys().contains(KEY));69 assertEquals(VALUE, cache.get(FQN, KEY));70 assertEquals(0, cache.getNumberOfLocksHeld());71 tm.commit();72 }73 public void testWithTransactionsRepeatableRead() throws Exception74 {75 UnitTestCacheFactory<String, String> instance = new UnitTestCacheFactory<String, String>();76 cache = (CacheSPI<String, String>) instance.createCache(false, getClass());77 cache.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);78 cache.getConfiguration().setIsolationLevel(IsolationLevel.REPEATABLE_READ);79 cache.getConfiguration().setNodeLockingScheme(Configuration.NodeLockingScheme.PESSIMISTIC);80 cache.getConfiguration().setTransactionManagerLookupClass(TransactionSetup.getManagerLookup());81 cache.start();82 tm = startTransaction();83 cache.put(FQN, KEY, VALUE);84 cache.put(FQN + "/d", KEY, VALUE);85 Node node = cache.peek(FQN, false, false);86 assertTrue(node != null && node.getKeys().contains(KEY));87 assertEquals(VALUE, cache.get(FQN, KEY));88 assertEquals(5, cache.getNumberOfLocksHeld());89 tm.commit();90 }91 private TransactionManager startTransaction() throws SystemException, NotSupportedException92 {93 TransactionManager mgr = cache.getTransactionManager();94 mgr.begin();...
Source:CacheModeLocalSimpleTest.java
...57 private void doTest(boolean optimistic) throws Exception58 {59 if (optimistic)60 {61 cache1.getConfiguration().setNodeLockingScheme(Configuration.NodeLockingScheme.OPTIMISTIC);62 cache2.getConfiguration().setNodeLockingScheme(Configuration.NodeLockingScheme.OPTIMISTIC);63 cache1.getConfiguration().setSyncCommitPhase(true);64 cache1.getConfiguration().setSyncRollbackPhase(true);65 cache2.getConfiguration().setSyncCommitPhase(true);66 cache2.getConfiguration().setSyncRollbackPhase(true);67 }68 cache1.start();69 cache2.start();70 TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);71 TransactionManager mgr = cache1.getTransactionManager();72 mgr.begin();73 cache1.put(Fqn.fromString("/replicate"), "k", "v");74 cache1.getInvocationContext().getOptionOverrides().setCacheModeLocal(true);75 cache1.put(Fqn.fromString("/not-replicate"), "k", "v");76 mgr.commit();77 Thread.sleep(3000);78 assertEquals("v", cache1.get("/replicate", "k"));79 assertEquals("v", cache1.get("/not-replicate", "k"));80 assertEquals("v", cache2.get("/replicate", "k"));...
Source:BadMuxConfigTest.java
...59 }60 public void testMissingMuxChannelFactory() throws Exception61 {62 muxHelper.configureCacheForMux(cache);63 cache.getConfiguration().getRuntimeConfig().setMuxChannelFactory(null);64 checkStart(false, false);65 }66 public void testInvalidStackName() throws Exception67 {68 muxHelper.configureCacheForMux(cache);69 cache.getConfiguration().setMultiplexerStack("bogus");70 checkStart(true, false);71 }72 public void testMissingStackName() throws Exception73 {74 muxHelper.configureCacheForMux(cache);75 cache.getConfiguration().setMultiplexerStack(null);76 checkStart(true, false);77 }78 private void checkStart(boolean expectFail, boolean expectMux)79 {80 try81 {82 cache.start();83 cacheStarted = true;84 if (expectFail)85 {86 fail("Start did not fail as expected");87 }88 if (expectMux)89 {90 assertTrue("Cache is using mux", cache.getConfiguration().isUsingMultiplexer());91 }92 else93 {94 assertFalse("Cache is not using mux ", cache.getConfiguration().isUsingMultiplexer());95 }96 }97 catch (Exception e)98 {99 if (!expectFail)100 {101 fail("Caught exception starting cache " + e.getLocalizedMessage());102 }103 }104 }105}...
Source:ConcurrentPassivationTest.java
...30 @BeforeMethod(alwaysRun = true)31 public void setUp() throws Exception32 {33 initCaches();34 wakeupIntervalMillis = cache.getConfiguration().getEvictionConfig().getWakeupInterval();35 if (wakeupIntervalMillis < 0)36 {37 fail("testEviction(): eviction thread wake up interval is illegal " + wakeupIntervalMillis);38 }39 }40 private void initCaches()41 {42 UnitTestCacheFactory<String, String> instance = new UnitTestCacheFactory<String, String>();43 cache = (CacheSPI) instance.createCache(new XmlConfigurationParser().parseFile("configs/local-passivation.xml"), false, getClass());44 cache.getConfiguration().setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");45 cache.getConfiguration().getCacheLoaderConfig().getFirstCacheLoaderConfig().setClassName(DummyInMemoryCacheLoader.class.getName());46 cache.start();47 }48 @AfterMethod(alwaysRun = true)49 public void tearDown() throws Exception50 {51 TestingUtil.killCaches(cache);52 cache = null;53 }54 public void testConcurrentPassivation() throws Exception55 {56 Fqn base = Fqn.fromElements("/org/jboss/test/data/concurrent/passivation");57 // Create a bunch of nodes; more than the /org/jboss/test/data58 // region's maxNodes so we know eviction will kick in59 for (int i = 0; i < 35000; i++)...
Source:RemoteTestNG6_9_7.java
...19 @Override20 public TestRunner newTestRunner(ISuite suite, XmlTest xmlTest,21 Collection<IInvokedMethodListener> listeners) {22 TestRunner runner =23 new TestRunner(getConfiguration(), suite, xmlTest,24 false /*skipFailedInvocationCounts */,25 listeners);26 if (m_useDefaultListeners) {27 runner.addListener(new TestHTMLReporter());28 runner.addListener(new JUnitXMLReporter());29 }30 for (IConfigurationListener cl : getConfiguration().getConfigurationListeners()) {31 runner.addListener(cl);32 }33 return runner;34 }35 };36 }37 return m_customTestRunnerFactory;38 }39 @Override40 protected ITestRunnerFactory createDelegatingTestRunnerFactory(ITestRunnerFactory trf, MessageHub smsh) {41 return new DelegatingTestRunnerFactory(trf, smsh);42 }43 private static class DelegatingTestRunnerFactory implements ITestRunnerFactory {44 private final ITestRunnerFactory m_delegateFactory;...
Source:DontRunTestsWhenInitFailTest.java
...13import org.testng.annotations.Test;14public class DontRunTestsWhenInitFailTest {15 private static class TestClass extends FluentTestNg {16 TestClass() {17 getConfiguration().setScreenshotMode(TriggerMode.AUTOMATIC_ON_FAIL);18 getConfiguration().setHtmlDumpMode(TriggerMode.AUTOMATIC_ON_FAIL);19 }20 @Override21 public WebDriver newWebDriver() {22 HtmlUnitDriver driver = new HtmlUnitDriver(false);23 driver.get("invalid:url"); // Simulate a driver initialization failure.24 return driver;25 }26 @Test27 public void testDriverFailShouldNotCallTestMethod() {28 Assert.fail("Should not be called");29 }30 }31 @Test32 public void testRun() {...
getConfiguration
Using AI Code Generation
1public void test() {2 TestNG testng = new TestNG();3 testng.setTestClasses(new Class[] { TestClass.class });4 testng.setVerbose(1);5 testng.setUseDefaultListeners(false);6 testng.addListener(new MyTestListener());7 testng.run();8}9public void test() {10 TestNG testng = new TestNG();11 testng.setTestClasses(new Class[] { TestClass.class });12 testng.setVerbose(1);13 testng.setUseDefaultListeners(false);14 testng.addListener(new MyTestListener());15 testng.run();16}17public class TestClass {18 public void beforeMethod() {19 System.out.println("beforeMethod");20 }21 public void test() {22 System.out.println("test");23 }24 public void afterMethod() {25 System.out.println("afterMethod");26 }27}28public class MyTestListener extends TestListenerAdapter {29 public void onConfigurationSuccess(ITestResult itr) {30 System.out.println("onConfigurationSuccess");31 }32 public void onConfigurationFailure(ITestResult itr) {33 System.out.println("onConfigurationFailure");34 }35 public void onConfigurationSkip(ITestResult itr) {36 System.out.println("onConfigurationSkip");37 }38}
getConfiguration
Using AI Code Generation
1import org.testng.TestNG;2class TestNGDemo {3 public static void main(String[] args) {4 TestNG testNG = new TestNG();5 System.out.println(testNG.getConfiguration());6 }7}8Next Topic TestNG getTestName() Method
getConfiguration
Using AI Code Generation
1package com.test;2import org.testng.TestNG;3import org.testng.xml.XmlSuite;4import java.util.List;5public class TestNGConfig {6 public static void main(String[] args) {7 TestNG testng = new TestNG();8 testng.setTestSuites(List.of("testng.xml"));9 List<XmlSuite> suites = testng.getConfiguration();10 System.out.println(suites);11 }12}
getConfiguration
Using AI Code Generation
1import org.testng.TestNG;2import org.testng.xml.XmlSuite;3import java.util.List;4public class TestNGTest {5 public static void main(String[] args) {6 TestNG testNG = new TestNG();7 testNG.setTestSuites(List.of("testng.xml"));8 testNG.run();9 List<XmlSuite> suites = testNG.getConfiguration();10 suites.forEach(suite -> {11 System.out.println("suite name: " + suite.getName());12 suite.getTests().forEach(test -> {13 System.out.println("test name: " + test.getName());14 test.getGroups().forEach(group -> {15 System.out.println("test group: " + group);16 });17 test.getParameters().forEach(parameter -> {18 System.out.println("test parameter: " + parameter.getName());19 });20 });21 });22 }23}
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!!