Best Testng code snippet using org.testng.SuiteRunner.getAttribute
Source:SuiteRunner.java  
...524    }525  }526  private IAttributes m_attributes = new Attributes();527  @Override528  public Object getAttribute(String name) {529    return m_attributes.getAttribute(name);530  }531  @Override532  public void setAttribute(String name, Object value) {533    m_attributes.setAttribute(name, value);534  }535  @Override536  public Set<String> getAttributeNames() {537    return m_attributes.getAttributeNames();538  }539  @Override540  public Object removeAttribute(String name) {541    return m_attributes.removeAttribute(name);542  }543  /////544  // implements IInvokedMethodListener545  //546  @Override547  public void afterInvocation(IInvokedMethod method, ITestResult testResult) {548  }549  @Override550  public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {551    if (method == null) {...Source:NginxRebindIntegrationTest.java  
...118        119        // Start the app, and ensure reachable; start polling the URL120        origApp.start(ImmutableList.of(localhostProvisioningLocation));121        122        String rootUrl = origNginx.getAttribute(NginxController.ROOT_URL);123        int nginxPort = origNginx.getAttribute(NginxController.PROXY_HTTP_PORT);124        125        assertHttpStatusCodeEventuallyEquals(rootUrl, 404);126        WebAppMonitor monitor = newWebAppMonitor(rootUrl, 404);127        final String origConfigFile = origNginx.getConfigFile();128        129        newApp = rebind(RebindOptions.create().terminateOrigManagementContext(true));130        final NginxController newNginx = (NginxController) Iterables.find(newApp.getChildren(), Predicates.instanceOf(NginxController.class));131        assertEquals(newNginx.getConfigFile(), origConfigFile);132        133        EntityTestUtils.assertAttributeEqualsEventually(newNginx, NginxController.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);134        assertEquals(newNginx.getAttribute(NginxController.PROXY_HTTP_PORT), (Integer)nginxPort);135        assertEquals(newNginx.getAttribute(NginxController.ROOT_URL), rootUrl);136        assertEquals(newNginx.getAttribute(NginxController.PROXY_HTTP_PORT), origNginx.getAttribute(NginxController.PROXY_HTTP_PORT));137        assertEquals(newNginx.getConfig(NginxController.STICKY), origNginx.getConfig(NginxController.STICKY));138        139        assertAttributeEqualsEventually(newNginx, SoftwareProcess.SERVICE_UP, true);140        assertHttpStatusCodeEventuallyEquals(rootUrl, 404);141        142        assertEquals(monitor.getFailures(), 0);143    }144    145    /*146        Exception java.lang.NoClassDefFoundError147        148        Message: org/apache/brooklyn/test/HttpTestUtils$3149        Stacktrace:150        151        152        at org.apache.brooklyn.test.HttpTestUtils.assertHttpStatusCodeEventuallyEquals(HttpTestUtils.java:208)153        at org.apache.brooklyn.test.HttpTestUtils.assertHttpStatusCodeEventuallyEquals(HttpTestUtils.java:204)154        at org.apache.brooklyn.entity.proxy.nginx.NginxRebindIntegrationTest.testRebindsWithoutLosingServerPool(NginxRebindIntegrationTest.java:178)155        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)156        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)157        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)158        at java.lang.reflect.Method.invoke(Method.java:606)159        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)160        at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)161        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)162        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)163        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)164        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)165        at org.testng.TestRunner.privateRun(TestRunner.java:767)166        at org.testng.TestRunner.run(TestRunner.java:617)167        at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)168        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)169        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)170        at org.testng.SuiteRunner.run(SuiteRunner.java:254)171        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)172        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)173        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)174        at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)175        at org.testng.TestNG.run(TestNG.java:1057)176        at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:115)177        at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:205)178        at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:108)179        at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:111)180        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)181        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)182        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)183     */184    /**185     * Test can rebind with an active server pool.186     */187    @Test(groups = {"Integration","Broken"})188    public void testRebindsWithoutLosingServerPool() throws Exception {189        190        // Set up nginx with a server pool191        DynamicCluster origServerPool = origApp.createAndManageChild(EntitySpec.create(DynamicCluster.class)192                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(Tomcat8Server.class).configure("war", getTestWar()))193                .configure("initialSize", 1));194        195        NginxController origNginx = origApp.createAndManageChild(EntitySpec.create(NginxController.class)196                .configure("serverPool", origServerPool)197                .configure("domain", "localhost"));198        199        // Start the app, and ensure reachable; start polling the URL200        origApp.start(ImmutableList.of(localhostProvisioningLocation));201        202        String rootUrl = origNginx.getAttribute(NginxController.ROOT_URL);203        Tomcat8Server origServer = (Tomcat8Server) Iterables.getOnlyElement(origServerPool.getMembers());204        assertEquals(origNginx.getAttribute(NginxController.SERVER_POOL_TARGETS).keySet(), ImmutableSet.of(origServer));205        206        assertHttpStatusCodeEventuallyEquals(rootUrl, 200);207        WebAppMonitor monitor = newWebAppMonitor(rootUrl, 200);208        final String origConfigFile = origNginx.getConfigFile();209        210        // Rebind211        newApp = rebind(RebindOptions.create().terminateOrigManagementContext(true));212        ManagementContext newManagementContext = newApp.getManagementContext();213        final NginxController newNginx = (NginxController) Iterables.find(newApp.getChildren(), Predicates.instanceOf(NginxController.class));214        final DynamicCluster newServerPool = (DynamicCluster) newManagementContext.getEntityManager().getEntity(origServerPool.getId());215        final Tomcat8Server newServer = (Tomcat8Server) Iterables.getOnlyElement(newServerPool.getMembers());216        // Expect continually to have same nginx members; should not lose them temporarily!217        Asserts.succeedsContinually(new Runnable() {218            public void run() {219                Map<Entity, String> newNginxMemebers = newNginx.getAttribute(NginxController.SERVER_POOL_TARGETS);220                assertEquals(newNginxMemebers.keySet(), ImmutableSet.of(newServer));221            }});222        223        224        assertAttributeEqualsEventually(newNginx, SoftwareProcess.SERVICE_UP, true);225        assertHttpStatusCodeEventuallyEquals(rootUrl, 200);226        assertEquals(newNginx.getConfigFile(), origConfigFile);227        228        // Check that an update doesn't break things229        newNginx.update();230        assertHttpStatusCodeEquals(rootUrl, 200);231        // Resize new cluster, and confirm change takes affect.232        //  - Increase size233        //  - wait for nginx to definitely be updates (TODO nicer way to wait for updated?)234        //  - terminate old server235        //  - confirm can still route messages236        newServerPool.resize(2);237        238        Thread.sleep(10*1000);239        240        newServer.stop();241        assertHttpStatusCodeEventuallyEquals(rootUrl, 200);242        // Check that URLs have been constantly reachable243        assertEquals(monitor.getFailures(), 0);244    }245    246    /*247        Exception java.lang.NoClassDefFoundError248        249        Message: org/apache/brooklyn/test/HttpTestUtils$3250        Stacktrace:251        252        253        at org.apache.brooklyn.test.HttpTestUtils.assertHttpStatusCodeEventuallyEquals(HttpTestUtils.java:208)254        at org.apache.brooklyn.test.HttpTestUtils.assertHttpStatusCodeEventuallyEquals(HttpTestUtils.java:204)255        at org.apache.brooklyn.entity.proxy.nginx.NginxRebindIntegrationTest.testRebindsWithoutLosingUrlMappings(NginxRebindIntegrationTest.java:254)256        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)257        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)258        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)259        at java.lang.reflect.Method.invoke(Method.java:606)260        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)261        at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)262        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)263        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)264        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)265        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)266        at org.testng.TestRunner.privateRun(TestRunner.java:767)267        at org.testng.TestRunner.run(TestRunner.java:617)268        at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)269        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)270        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)271        at org.testng.SuiteRunner.run(SuiteRunner.java:254)272        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)273        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)274        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)275        at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)276        at org.testng.TestNG.run(TestNG.java:1057)277        at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:115)278        at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:205)279        at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:108)280        at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:111)281        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)282        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)283        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)284     */285    /**286     * Test can rebind to the with server pool and URL remappings.287     * NOTE: This requires a redirection from localhost1 to 127.0.0.1 in your /etc/hosts file288     */289    @Test(groups = {"Integration","Broken"})290    public void testRebindsWithoutLosingUrlMappings() throws Exception {291        292        // Set up nginx with a url-mapping293        Group origUrlMappingsGroup = origApp.createAndManageChild(EntitySpec.create(BasicGroup.class)294                .configure("childrenAsMembers", true));295        296        DynamicCluster origServerPool = origApp.createAndManageChild(EntitySpec.create(DynamicCluster.class)297                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(Tomcat8Server.class).configure("war", getTestWar()))298                .configure("initialSize", 1)); 299        UrlMapping origMapping = origUrlMappingsGroup.addChild(EntitySpec.create(UrlMapping.class)300                .configure("domain", "localhost1")301                .configure("target", origServerPool)302                .configure("rewrites", ImmutableList.of(new UrlRewriteRule("/foo/(.*)", "/$1"))));303        304        NginxController origNginx = origApp.createAndManageChild(EntitySpec.create(NginxController.class)305                .configure("domain", "localhost")306                .configure("urlMappings", origUrlMappingsGroup));307        // Start the app, and ensure reachable; start polling the URL308        origApp.start(ImmutableList.of(localhostProvisioningLocation));309        310        String mappingGroupUrl = "http://localhost1:"+origNginx.getAttribute(NginxController.PROXY_HTTP_PORT)+"/foo/";311        assertHttpStatusCodeEventuallyEquals(mappingGroupUrl, 200);312        WebAppMonitor monitor = newWebAppMonitor(mappingGroupUrl, 200);313        final String origConfigFile = origNginx.getConfigFile();314        315        // Create a rebinding316        newApp = rebind(RebindOptions.create().terminateOrigManagementContext(true));317        ManagementContext newManagementContext = newApp.getManagementContext();318        final NginxController newNginx = (NginxController) Iterables.find(newApp.getChildren(), Predicates.instanceOf(NginxController.class));319        DynamicCluster newServerPool = (DynamicCluster) newManagementContext.getEntityManager().getEntity(origServerPool.getId());320        Tomcat8Server newServer = (Tomcat8Server) Iterables.getOnlyElement(newServerPool.getMembers());321        322        assertAttributeEqualsEventually(newNginx, SoftwareProcess.SERVICE_UP, true);323        assertHttpStatusCodeEventuallyEquals(mappingGroupUrl, 200);324        ...Source:ControlledDynamicWebAppClusterRebindIntegrationTest.java  
...148                .configure("initialSize", 1)149                .configure("controller", origNginx));150        151        origApp.start(ImmutableList.of(localhostProvisioningLocation));152        String rootUrl = origNginx.getAttribute(JBoss7Server.ROOT_URL);153        154        assertHttpStatusCodeEventuallyEquals(rootUrl, 200);155        WebAppMonitor monitor = newWebAppMonitor(rootUrl);156        157        // Rebind158        newApp = rebind();159        NginxController newNginx = (NginxController) Iterables.find(newApp.getChildren(), Predicates.instanceOf(NginxController.class));160        ControlledDynamicWebAppCluster newCluster = (ControlledDynamicWebAppCluster) Iterables.find(newApp.getChildren(), Predicates.instanceOf(ControlledDynamicWebAppCluster.class));161        assertAttributeEqualsEventually(newNginx, SoftwareProcess.SERVICE_UP, true);162        assertHttpStatusCodeEquals(rootUrl, 200);163        // Confirm the cluster is usable: we can scale-up164        assertEquals(newCluster.getCurrentSize(), (Integer)1);165        newCluster.resize(2);166        ...Source:DynamicWebAppClusterRebindIntegrationTest.java  
...144                .configure("initialSize", 1));145        146        origApp.start(ImmutableList.of(localhostProvisioningLocation));147        JBoss7Server origJboss = (JBoss7Server) Iterables.find(origCluster.getChildren(), Predicates.instanceOf(JBoss7Server.class));148        String jbossUrl = origJboss.getAttribute(JBoss7Server.ROOT_URL);149        150        assertHttpStatusCodeEventuallyEquals(jbossUrl, 200);151        WebAppMonitor monitor = newWebAppMonitor(jbossUrl);152        153        // Rebind154        newApp = rebind();155        DynamicWebAppCluster newCluster = (DynamicWebAppCluster) Iterables.find(newApp.getChildren(), Predicates.instanceOf(DynamicWebAppCluster.class));156        assertHttpStatusCodeEquals(jbossUrl, 200);157        // Confirm the cluster is usable: we can scale-up158        assertEquals(newCluster.getCurrentSize(), (Integer)1);159        newCluster.resize(2);160        Iterable<Entity> newJbosses = Iterables.filter(newCluster.getChildren(), Predicates.instanceOf(JBoss7Server.class));161        assertEquals(Iterables.size(newJbosses), 2);162        for (Entity j : newJbosses) {163            assertHttpStatusCodeEventuallyEquals(j.getAttribute(JBoss7Server.ROOT_URL), 200);164        }165        // Ensure while doing all of this the original jboss server remained reachable166        assertEquals(monitor.getFailures(), 0);167        168        // Ensure cluster is usable: we can scale back to stop the original jboss server169        newCluster.resize(0);170        171        assertUrlUnreachableEventually(jbossUrl);172    }173}...Source:DataStoreTestSuiteListener.java  
...84		85		suiteRunner=(SuiteRunner) suite;86		suiteRunner.setAttribute("helper", helper);87		88		obj=suiteRunner.getAttribute("helper");89		if (90				(obj != null) && 91				(obj instanceof LocalServiceTestHelper)92		   ) {93			helper=(LocalServiceTestHelper) obj;94			helper.tearDown();95		} // END if ((obj != null) && (obj instanceof LocalServiceTestHelper))96		logger.exiting(_CLASS, "onFinish(ISuite)");97	}98}...getAttribute
Using AI Code Generation
1package com.qa.test;2import java.io.File;3import java.io.IOException;4import java.lang.reflect.Method;5import java.util.ArrayList;6import java.util.List;7import org.testng.IReporter;8import org.testng.ISuite;9import org.testng.ISuiteResult;10import org.testng.ITestContext;11import org.testng.ITestNGMethod;12import org.testng.ITestResult;13import org.testng.Reporter;14import org.testng.TestListenerAdapter;15import org.testng.TestNG;16import org.testng.xml.XmlClass;17import org.testng.xml.XmlSuite;18import org.testng.xml.XmlTest;19import com.github.mkolisnyk.cucumber.reporting.CucumberResultsOverview;20import com.github.mkolisnyk.cucumber.reporting.CucumberUsageReporting;21import com.github.mkolisnyk.cucumber.reporting.types.breakdown.BreakdownReport;22import com.github.mkolisnyk.cucumber.reporting.types.breakdown.BreakdownReportModel;23import com.github.mkolisnyk.cucumber.reporting.types.breakdown.data.BreakdownData;24import com.github.mkolisnyk.cucumber.reporting.types.breakdown.data.BreakdownDataItem;25import com.github.mkolisnyk.cucumber.reporting.types.breakdown.matching.BreakdownMatch;26import com.github.mkolisnyk.cucumber.reporting.types.breakdown.matching.BreakdownMatchItem;27import com.github.mkolisnyk.cucumber.reporting.types.result.CucumberFeatureResult;28import com.github.mkolisnyk.cucumber.reporting.types.result.CucumberScenarioResult;29import com.github.mkolisnyk.cucumber.reporting.types.result.CucumberStepResult;30import com.github.mkolisnyk.cucumber.runner.runtime.ExtendedRuntimeOptions;31import com.github.mkolisnyk.cucumber.runner.runtime.ExtendedRuntimeOptions.ExecutionMode;32import com.github.mkolisnyk.cucumber.runner.runtime.ExtendedRuntimeOptions.OutputFormat;33import com.github.mkolisnyk.cucumber.runner.runtime.ExtendedRuntimeOptions.OutputType;34import cucumber.api.CucumberOptions;35import cucumber.api.junit.Cucumber;36import cucumber.runtime.Runtime;37import cucumber.runtime.RuntimeOptions;38import cucumber.runtime.formatter.PluginFactory;39import cucumber.runtime.formatter.Plugins;40import cucumber.runtime.model.CucumberFeature;41import cucumber.runtime.model.CucumberScenario;42import cucumber.runtime.model.CucumberScenarioOutline;43import cucumber.runtime.model.CucumberTagStatement;44import gherkin.formatter.Formatter;45import gherkin.formatter.Reporter;46import gherkin.formatter.model.Result;47import gherkin.formatter.model.Step;getAttribute
Using AI Code Generation
1package testng;2import org.testng.TestNG;3import org.testng.SuiteRunner;4import org.testng.xml.XmlSuite;5import java.util.List;6public class TestNGSuiteName {7    public static void main(String[] args) {8        TestNG testNG = new TestNG();9        testNG.setTestSuites(List.of("testng.xml"));10        testNG.run();11        List<XmlSuite> suites = testNG.getXmlSuites();12        suites.forEach(suite -> {13            SuiteRunner suiteRunner = new SuiteRunner(suite, null);14            System.out.println("Suite name: " + suiteRunner.getAttribute("name"));15        });16    }17}getAttribute
Using AI Code Generation
1import org.testng.SuiteRunner;2import org.testng.TestNG;3import org.testng.annotations.Test;4public class SuiteRunnerTest {5    public void testSuiteRunner() {6        TestNG testNG = new TestNG();7        testNG.setTestSuites(new String[]{"src/test/resources/testng.xml"});8        testNG.run();9        SuiteRunner suiteRunner = testNG.getSuiteRunnerMap().get("src/test/resources/testng.xml");10        System.out.println(suiteRunner.getAttribute("name"));11    }12}13import org.testng.ITestContext;14import org.testng.ITestNGMethod;15import org.testng.ITestResult;16import org.testng.TestNG;17import org.testng.annotations.Test;18public class TestRunnerTest {19    public void testTestRunner() {20        TestNG testNG = new TestNG();21        testNG.setTestSuites(new String[]{"src/test/resources/testng.xml"});22        testNG.run();23        SuiteRunner suiteRunner = testNG.getSuiteRunnerMap().get("src/test/resources/testng.xml");24        ITestNGMethod[] methods = suiteRunner.getAllTestMethods();25        for (ITestNGMethod method : methods) {26            if (method.getMethodName().equals("test")) {27                ITestContext context = suiteRunner.getTestContext(method);28                ITestResult result = context.getPassedTests().getAllResults().iterator().next();29                System.out.println(result.getMethod().getXmlTest().getParameter("url"));30            }31        }32    }33}34You can also get the value of a parameter of a test using the getParameter() method of the ITestContext class. For example, the following code gets the valueTestNG 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!!
