Best Testng code snippet using org.testng.TestRunner.getName
Source:SuiteRunner.java
...159 public XmlSuite getXmlSuite() {160 return m_suite;161 }162 @Override163 public String getName() {164 return m_suite.getName();165 }166 public void setObjectFactory(ITestObjectFactory objectFactory) {167 m_objectFactory = objectFactory;168 }169 public void setReportResults(boolean reportResults) {170 m_useDefaultListeners = reportResults;171 }172 private void invokeListeners(boolean start) {173 for (ISuiteListener sl : m_listeners.values()) {174 if (start) {175 sl.onStart(this);176 }177 else {178 sl.onFinish(this);179 }180 }181 }182 private void setOutputDir(String outputdir) {183 if (isStringBlank(outputdir) && m_useDefaultListeners) {184 outputdir = DEFAULT_OUTPUT_DIR;185 }186 m_outputDir = (null != outputdir) ? new File(outputdir).getAbsolutePath()187 : null;188 }189 private ITestRunnerFactory buildRunnerFactory() {190 ITestRunnerFactory factory = null;191 if (null == m_tmpRunnerFactory) {192 factory = new DefaultTestRunnerFactory(m_configuration,193 m_testListeners.toArray(new ITestListener[m_testListeners.size()]),194 m_useDefaultListeners, m_skipFailedInvocationCounts);195 }196 else {197 factory = new ProxyTestRunnerFactory(198 m_testListeners.toArray(new ITestListener[m_testListeners.size()]),199 m_tmpRunnerFactory);200 }201 return factory;202 }203 @Override204 public String getParallel() {205 return m_suite.getParallel().toString();206 }207 public String getParentModule() {208 return m_suite.getParentModule();209 }210 @Override211 public String getGuiceStage() {212 return m_suite.getGuiceStage();213 }214 public Injector getParentInjector() {215 return m_parentInjector;216 }217 public void setParentInjector(Injector injector) {218 m_parentInjector = injector;219 }220 @Override221 public void run() {222 invokeListeners(true /* start */);223 try {224 privateRun();225 }226 finally {227 invokeListeners(false /* stop */);228 }229 }230 private void privateRun() {231 // Map for unicity, Linked for guaranteed order232 Map<Method, ITestNGMethod> beforeSuiteMethods= new LinkedHashMap<>();233 Map<Method, ITestNGMethod> afterSuiteMethods = new LinkedHashMap<>();234 IInvoker invoker = null;235 // Get the invoker and find all the suite level methods236 for (TestRunner tr: m_testRunners) {237 // TODO: Code smell. Invoker should belong to SuiteRunner, not TestRunner238 // -- cbeust239 invoker = tr.getInvoker();240 for (ITestNGMethod m : tr.getBeforeSuiteMethods()) {241 beforeSuiteMethods.put(m.getMethod(), m);242 }243 for (ITestNGMethod m : tr.getAfterSuiteMethods()) {244 afterSuiteMethods.put(m.getMethod(), m);245 }246 }247 //248 // Invoke beforeSuite methods (the invoker can be null249 // if the suite we are currently running only contains250 // a <file-suite> tag and no real tests)251 //252 if (invoker != null) {253 if(beforeSuiteMethods.values().size() > 0) {254 invoker.invokeConfigurations(null,255 beforeSuiteMethods.values().toArray(new ITestNGMethod[beforeSuiteMethods.size()]),256 m_suite, m_suite.getParameters(), null, /* no parameter values */257 null /* instance */258 );259 }260 Utils.log("SuiteRunner", 3, "Created " + m_testRunners.size() + " TestRunners");261 //262 // Run all the test runners263 //264 boolean testsInParallel = XmlSuite.ParallelMode.TESTS.equals(m_suite.getParallel());265 if (!testsInParallel) {266 runSequentially();267 }268 else {269 runInParallelTestMode();270 }271// SuitePlan sp = new SuitePlan();272// for (TestRunner tr : m_testRunners) {273// sp.addTestPlan(tr.getTestPlan());274// }275// sp.dump();276 //277 // Invoke afterSuite methods278 //279 if (afterSuiteMethods.values().size() > 0) {280 invoker.invokeConfigurations(null,281 afterSuiteMethods.values().toArray(new ITestNGMethod[afterSuiteMethods.size()]),282 m_suite, m_suite.getAllParameters(), null, /* no parameter values */283 null /* instance */);284 }285 }286 }287 private List<IReporter> m_reporters = Lists.newArrayList();288 private void addReporter(IReporter listener) {289 m_reporters.add(listener);290 }291 void addConfigurationListener(IConfigurationListener listener) {292 m_configuration.addConfigurationListener(listener);293 }294 public List<IReporter> getReporters() {295 return m_reporters;296 }297 private void runSequentially() {298 for (TestRunner tr : m_testRunners) {299 runTest(tr);300 }301 }302 private void runTest(TestRunner tr) {303 tr.run();304 ISuiteResult sr = new SuiteResult(m_suite, tr);305 m_suiteResults.put(tr.getName(), sr);306 }307 /**308 * Implement <suite parallel="tests">.309 * Since this kind of parallelism happens at the suite level, we need a special code path310 * to execute it. All the other parallelism strategies are implemented at the test level311 * in TestRunner#createParallelWorkers (but since this method deals with just one <test>312 * tag, it can't implement <suite parallel="tests">, which is why we're doing it here).313 */314 private void runInParallelTestMode() {315 List<Runnable> tasks= Lists.newArrayList(m_testRunners.size());316 for(TestRunner tr: m_testRunners) {317 tasks.add(new SuiteWorker(tr));318 }319 ThreadUtil.execute(tasks, m_suite.getThreadCount(),320 m_suite.getTimeOut(XmlTest.DEFAULT_TIMEOUT_MS), false);321 }322 private class SuiteWorker implements Runnable {323 private TestRunner m_testRunner;324 public SuiteWorker(TestRunner tr) {325 m_testRunner = tr;326 }327 @Override328 public void run() {329 Utils.log("[SuiteWorker]", 4, "Running XML Test '"330 + m_testRunner.getTest().getName() + "' in Parallel");331 runTest(m_testRunner);332 }333 }334 /**335 * Registers ISuiteListeners interested in reporting the result of the current336 * suite.337 *338 * @param reporter339 */340 protected void addListener(ISuiteListener reporter) {341 m_listeners.put(reporter.getClass(), reporter);342 }343 @Override344 public void addListener(ITestNGListener listener) {345 if (listener instanceof IInvokedMethodListener) {346 IInvokedMethodListener invokedMethodListener = (IInvokedMethodListener) listener;347 m_invokedMethodListeners.put(invokedMethodListener.getClass(), invokedMethodListener);348 }349 if (listener instanceof ISuiteListener) {350 addListener((ISuiteListener) listener);351 }352 if (listener instanceof IReporter) {353 addReporter((IReporter) listener);354 }355 if (listener instanceof IConfigurationListener) {356 addConfigurationListener((IConfigurationListener) listener);357 }358 }359 @Override360 public String getOutputDirectory() {361 return m_outputDir + File.separatorChar + getName();362 }363 @Override364 public Map<String, ISuiteResult> getResults() {365 return m_suiteResults;366 }367 /**368 * FIXME: should be removed?369 *370 * @see org.testng.ISuite#getParameter(java.lang.String)371 */372 @Override373 public String getParameter(String parameterName) {374 return m_suite.getParameter(parameterName);375 }376 /**377 * @see org.testng.ISuite#getMethodsByGroups()378 */379 @Override380 public Map<String, Collection<ITestNGMethod>> getMethodsByGroups() {381 Map<String, Collection<ITestNGMethod>> result = Maps.newHashMap();382 for (TestRunner tr : m_testRunners) {383 ITestNGMethod[] methods = tr.getAllTestMethods();384 for (ITestNGMethod m : methods) {385 String[] groups = m.getGroups();386 for (String groupName : groups) {387 Collection<ITestNGMethod> testMethods = result.get(groupName);388 if (null == testMethods) {389 testMethods = Lists.newArrayList();390 result.put(groupName, testMethods);391 }392 testMethods.add(m);393 }394 }395 }396 return result;397 }398 /**399 * @see org.testng.ISuite#getInvokedMethods()400 */401 @Override402 public Collection<ITestNGMethod> getInvokedMethods() {403 return getIncludedOrExcludedMethods(true /* included */);404 }405 /**406 * @see org.testng.ISuite#getExcludedMethods()407 */408 @Override409 public Collection<ITestNGMethod> getExcludedMethods() {410 return getIncludedOrExcludedMethods(false/* included */);411 }412 private Collection<ITestNGMethod> getIncludedOrExcludedMethods(boolean included) {413 List<ITestNGMethod> result= Lists.newArrayList();414 for (TestRunner tr : m_testRunners) {415 Collection<ITestNGMethod> methods = included ? tr.getInvokedMethods() : tr.getExcludedMethods();416 for (ITestNGMethod m : methods) {417 result.add(m);418 }419 }420 return result;421 }422 @Override423 public IObjectFactory getObjectFactory() {424 return m_objectFactory instanceof IObjectFactory ? (IObjectFactory) m_objectFactory : null;425 }426 @Override427 public IObjectFactory2 getObjectFactory2() {428 return m_objectFactory instanceof IObjectFactory2 ? (IObjectFactory2) m_objectFactory : null;429 }430 /**431 * Returns the annotation finder for the given annotation type.432 * @return the annotation finder for the given annotation type.433 */434 @Override435 public IAnnotationFinder getAnnotationFinder() {436 return m_configuration.getAnnotationFinder();437 }438 public static void ppp(String s) {439 System.out.println("[SuiteRunner] " + s);440 }441 /**442 * The default implementation of {@link ITestRunnerFactory}.443 */444 private static class DefaultTestRunnerFactory implements ITestRunnerFactory {445 private ITestListener[] m_failureGenerators;446 private boolean m_useDefaultListeners;447 private boolean m_skipFailedInvocationCounts;448 private IConfiguration m_configuration;449 public DefaultTestRunnerFactory(IConfiguration configuration,450 ITestListener[] failureListeners,451 boolean useDefaultListeners,452 boolean skipFailedInvocationCounts)453 {454 m_configuration = configuration;455 m_failureGenerators = failureListeners;456 m_useDefaultListeners = useDefaultListeners;457 m_skipFailedInvocationCounts = skipFailedInvocationCounts;458 }459 @Override460 public TestRunner newTestRunner(ISuite suite, XmlTest test,461 Collection<IInvokedMethodListener> listeners, List<IClassListener> classListeners) {462 boolean skip = m_skipFailedInvocationCounts;463 if (! skip) {464 skip = test.skipFailedInvocationCounts();465 }466 TestRunner testRunner = new TestRunner(m_configuration, suite, test,467 suite.getOutputDirectory(), suite.getAnnotationFinder(), skip,468 listeners, classListeners);469 if (m_useDefaultListeners) {470 testRunner.addListener(new TestHTMLReporter());471 testRunner.addListener(new JUnitXMLReporter());472 //TODO: Moved these here because maven2 has output reporters running473 //already, the output from these causes directories to be created with474 //files. This is not the desired behaviour of running tests in maven2.475 //Don't know what to do about this though, are people relying on these476 //to be added even with defaultListeners set to false?477 testRunner.addListener(new TextReporter(testRunner.getName(), TestRunner.getVerbose()));478 }479 for (ITestListener itl : m_failureGenerators) {480 testRunner.addListener(itl);481 }482 for (IConfigurationListener cl : m_configuration.getConfigurationListeners()) {483 testRunner.addConfigurationListener(cl);484 }485 return testRunner;486 }487 }488 private static class ProxyTestRunnerFactory implements ITestRunnerFactory {489 private ITestListener[] m_failureGenerators;490 private ITestRunnerFactory m_target;491 public ProxyTestRunnerFactory(ITestListener[] failureListeners, ITestRunnerFactory target) {492 m_failureGenerators = failureListeners;493 m_target= target;494 }495 @Override496 public TestRunner newTestRunner(ISuite suite, XmlTest test,497 Collection<IInvokedMethodListener> listeners, List<IClassListener> classListeners) {498 TestRunner testRunner= m_target.newTestRunner(suite, test, listeners, classListeners);499 testRunner.addListener(new TextReporter(testRunner.getName(), TestRunner.getVerbose()));500 for (ITestListener itl : m_failureGenerators) {501 testRunner.addListener(itl);502 }503 return testRunner;504 }505 }506 public void setHost(String host) {507 m_host = host;508 }509 @Override510 public String getHost() {511 return m_host;512 }513 private SuiteRunState m_suiteState= new SuiteRunState();...
Source:DynamicGraphHelper.java
...96 // Note: use a List here to preserve the ordering but make sure97 // we don't add the same class twice98 List<XmlClass> sortedClasses = Lists.newArrayList();99 for (XmlClass c : test.getXmlClasses()) {100 classes.put(c.getName(), new ArrayList<>());101 if (!sortedClasses.contains(c)) {102 sortedClasses.add(c);103 }104 }105 // Sort the classes based on their order of appearance in the XML106 sortedClasses.sort(classComparator());107 Map<String, Integer> indexedClasses1 = Maps.newHashMap();108 Map<Integer, String> indexedClasses2 = Maps.newHashMap();109 int i = 0;110 for (XmlClass c : sortedClasses) {111 indexedClasses1.put(c.getName(), i);112 indexedClasses2.put(i, c.getName());113 i++;114 }115 ListMultiMap<String, ITestNGMethod> methodsFromClass = Maps.newListMultiMap();116 for (ITestNGMethod m : methods) {117 methodsFromClass.put(m.getTestClass().getName(), m);118 }119 ListMultiMap<ITestNGMethod, ITestNGMethod> result = Maps.newListMultiMap();120 for (ITestNGMethod m : methods) {121 String name = m.getTestClass().getName();122 Integer index = indexedClasses1.get(name);123 // The index could be null if the classes listed in the XML are different124 // from the methods being run (e.g. the .xml only contains a factory that125 // instantiates methods from a different class). In this case, we cannot126 // perform any ordering.127 if (index != null && index > 0) {128 // Make this method depend on all the methods of the class in the previous129 // index130 String classDependedUpon = indexedClasses2.get(index - 1);131 List<ITestNGMethod> methodsDependedUpon = methodsFromClass.get(classDependedUpon);132 for (ITestNGMethod mdu : methodsDependedUpon) {133 result.put(mdu, m);134 }135 }...
Source:TestListner.java
...32 }33 public void onTestStart(ITestResult result) {34 // TODO Auto-generated method stub35 Reporter.log("*******************************************************************", true);36 Reporter.log("TEST CASE : " + result.getName().replace("_", " "), true);37 Reporter.log("*******************************************************************", true);38 ExtentTest test = null;39 if (TestRunner.parentExtentMap == null || TestRunner.parentExtentMap.isEmpty() || !TestRunner.parentExtentMap.containsKey(result.getName().replace("_", " "))) {40 TestRunner.parentExtentMap.put(result.getName().replace("_", " "), Framework.extentReports.startTest(result.getName().replace("_", " ")));41 }42 test = TestRunner.parentExtentMap.get(result.getName().replace("_", " "));43 testing.set(test);44 }45 public void onTestSuccess(ITestResult result) {46 if(!extentMap.get().isEmpty()) {47 for (String key : extentMap.get().keySet()) {48 // System.out.println(extentMap.get());49 // System.out.println(key);50 if (key.contains("child")) {51 TestRunner.parentExtentMap.get(result.getName().replace("_", " ")).appendChild((ExtentTest) extentMap.get().get(key));52 }53 }54 Framework.extentReports.endTest(TestRunner.parentExtentMap.get(result.getName().replace("_", " ")));55 extentMap.get().clear();56 }57 }58 public void onTestFailure(ITestResult result) {59 if(!extentMap.get().isEmpty()){60 for(String key:extentMap.get().keySet())61 {62 // System.out.println( key);63 if( key.contains("child"))64 {65 //extentMap.get().get("parent").appendChild((ExtentTest) extentMap.get().get(key));66 TestRunner.parentExtentMap.get(result.getName().replace("_", " ")).appendChild((ExtentTest) extentMap.get().get(key));67 }68 }69 Framework.extentReports.endTest(TestRunner.parentExtentMap.get(result.getName().replace("_", " ")));70 extentMap.get().clear();71 System.out.println("failed method end");72 }73 }74 public void onTestSkipped(ITestResult result) {75 for(String key:extentMap.get().keySet()){76 // System.out.println( key);77 if( key.contains("child"))78 {79 //extentMap.get().get("parent").appendChild((ExtentTest) extentMap.get().get(key));80 TestRunner.parentExtentMap.get(result.getName().replace("_", " ")).appendChild((ExtentTest) extentMap.get().get(key));81 }82 }83 //Framework.extentReports.endTest(TestRunner.parentExtentMap.get(result.getName().replace("_", " ")));84 extentMap.get().clear();85 }86 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {87 // TODO Auto-generated method stub88 }89 public void onStart(ITestContext context) {90 // TODO Auto-generated method stub91 }92}...
Source:TestRunnerWithTestNG.java
...49 driver = new ChromeDriver();50 testRunner = new TestNGCucumberRunner(TestRunnerWithTestNG.class);51 features = testRunner.getFeatures();52 for (CucumberFeature f : features) {53 featuresList.add(f.getGherkinFeature().getName());54 // featuresTagsList.put(f.getGherkinFeature().getName(),55 // f.getGherkinFeature().getTags());56 // featureElementList.put(f.getGherkinFeature().getName(),57 // f.getFeatureElements());58 List<CucumberTagStatement> featureElementsList = f.getFeatureElements();59 for (CucumberTagStatement t : featureElementsList) {60 if (t.getVisualName().contains("Scenario:")) {61 scenariosList.add(t.getVisualName().replace("Scenario:", "").trim());62 System.out.println(t.getGherkinModel());63 }64 if (t.getVisualName().contains("Scenario Outline:")) {65 scenarioOutlinesList.add(t.getVisualName().replace("Scenario Outline:", "").trim());66 }67 }68 }69 }70 @Test(dataProvider = "features")...
Source:TestRunner.java
...68 @AfterMethod69 public void getResult(ITestResult testResult) throws IOException {70 if (testResult.getStatus() == ITestResult.SKIP) {71 System.out.println("Skipped extent report");72 extentTest.skip(MarkupHelper.createLabel(testResult.getName() + " Test Case SKIPPED", ExtentColor.BLUE));73 extentTest.skip(testResult.getThrowable());74 // extentTest.log(Status.SKIP, MarkupHelper.createLabel(testResult.getName() + "75 // - Test Case Skipped", ExtentColor.ORANGE));76 } else if (testResult.getStatus() == ITestResult.FAILURE) {77 extentTest.fail(MarkupHelper.createLabel(testResult.getName() + " Test case FAILED due to below issues:",78 ExtentColor.RED));79 extentTest.fail(testResult.getThrowable());80 String screenshotPath = CommonUtil.takesScreenShotFailed(driver, testResult.getName());81 extentTest.addScreenCaptureFromPath(screenshotPath);82 } else if (testResult.getStatus() == ITestResult.SUCCESS) {83 extentTest.pass(MarkupHelper.createLabel(testResult.getName() + " Test Case PASSED", ExtentColor.GREEN));84 String screenshotPath = CommonUtil.takesScreenShot(driver, testResult.getName());8586 extentTest.addScreenCaptureFromPath(screenshotPath);87 }8889 }9091}
...
getName
Using AI Code Generation
1import org.testng.TestNG;2import org.testng.TestRunner;3public class TestRunnerDemo {4public static void main(String[] args) {5 TestNG testNG = new TestNG();6 testNG.setTestClasses(new Class[] { TestClass.class });7 TestRunner testRunner = testNG.createTestRunner();8 System.out.println(testRunner.getName());9}10}
getName
Using AI Code Generation
1import org.testng.TestRunner2import org.testng.ITestResult3import org.testng.ITestContext4import org.testng.ITestNGMethod5import org.testng.xml.XmlTest6import org.testng.xml.XmlSuite7import org.testng.xml.XmlClass8import org.testng.xml.XmlInclude9def getTestName() {10 def testRunner = new TestRunner()11 def testResult = testRunner.getCurrentTestResult()12 def testContext = testResult.getTestContext()13 def testNGMethod = testResult.getMethod()14 def xmlTest = testContext.getCurrentXmlTest()15 def xmlSuite = xmlTest.getSuite()16 def xmlClass = testNGMethod.getTestClass().getXmlClass()17 def xmlInclude = testNGMethod.getXmlTest().getIncludedMethods().find{it.getMethodName() == testNGMethod.getMethodName()}18}19def getTestName2() {20 def testRunner = new TestRunner()21 def testResult = testRunner.getCurrentTestResult()22 def testContext = testResult.getTestContext()23 def testNGMethod = testResult.getMethod()24 def xmlTest = testContext.getCurrentXmlTest()25 def xmlSuite = xmlTest.getSuite()26 def xmlClass = testNGMethod.getTestClass().getXmlClass()27 def xmlInclude = testNGMethod.getXmlTest().getIncludedMethods().find{it.getMethodName() == testNGMethod.getMethodName()}28}29def getTestName3() {30 def testRunner = new TestRunner()31 def testResult = testRunner.getCurrentTestResult()32 def testContext = testResult.getTestContext()33 def testNGMethod = testResult.getMethod()34 def xmlTest = testContext.getCurrentXmlTest()35 def xmlSuite = xmlTest.getSuite()36 def xmlClass = testNGMethod.getTestClass().getXmlClass()37 def xmlInclude = testNGMethod.getXmlTest().getIncludedMethods().find{it.getMethodName() == testNGMethod.getMethodName()}38}
getName
Using AI Code Generation
1String currentTestName = org.testng.TestRunner.getCurrentTest().getName();2log.info("Current test name is: " + currentTestName);3String currentTestName = org.testng.TestRunner.getCurrentTest().getTestName();4log.info("Current test name is: " + currentTestName);5String currentTestName = org.testng.TestRunner.getCurrentTest().getTestName();6log.info("Current test name is: " + currentTestName);7Code language: Java ( java )
getName
Using AI Code Generation
1def testname = org.testng.TestRunner().getName()2def extent = ExtentReports.getExtentReports()3def test = extent.startTest(testname)4test.log(LogStatus.INFO, "Test Started")5test.log(LogStatus.INFO, "Test Ended")6extent.endTest(test)7extent.flush()8dependencies {9}
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!!