Best Testng code snippet using org.testng.Interface ITestContext.getName
Source:AbstractChainedListener.java  
...60    61    Set<String> interceptor = Collections.synchronizedSet(new HashSet<String>());62    @Override63    public void onConfigurationSuccess(ITestResult itr) {64        configSuccess.add(itr.getName());65    }66    @Override67    public void onConfigurationFailure(ITestResult itr) {68        configFailure.add(itr.getName());69    }70    @Override71    public void onConfigurationSkip(ITestResult itr) {72        configSkipped.add(itr.getName());73    }74    // @Override omitted to avoid interface conflict75    public void beforeConfiguration(ITestResult tr) {76        beforeConfig.add(tr.getName());77    }78    79    @Override80    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {81        if (method.getTestMethod().isBeforeMethodConfiguration()) {82            beforeMethodBefore.add(testResult.getName());83        } else if (method.isTestMethod()) {84            testMethodBefore.add(testResult.getName());85        } else if (method.getTestMethod().isAfterMethodConfiguration()) {86            afterMethodBefore.add(testResult.getName());87        }88    }89    @Override90    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {91        if (method.getTestMethod().isBeforeMethodConfiguration()) {92            beforeMethodAfter.add(testResult.getName());93        } else if (method.isTestMethod()) {94            testMethodAfter.add(testResult.getName());95        } else if (method.getTestMethod().isAfterMethodConfiguration()) {96            afterMethodAfter.add(testResult.getName());97        }98    }99    @Override100    public void onBeforeClass(ITestClass testClass) {101        beforeClass.add(testClass.getRealClass().getSimpleName());102    }103    @Override104    public void onAfterClass(ITestClass testClass) {105        afterClass.add(testClass.getRealClass().getSimpleName());106    }107    @Override108    public void onTestStart(ITestResult result) {109        testStarted.add(result.getName());110    }111    @Override112    public void onTestSuccess(ITestResult result) {113        testSuccess.add(result.getName());114    }115    @Override116    public void onTestFailure(ITestResult result) {117        testFailure.add(result.getName());118    }119    @Override120    public void onTestSkipped(ITestResult result) {121        testSkipped.add(result.getName());122    }123    @Override124    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {125        testCurved.add(result.getName());126    }127    @Override128    public void onStart(ITestContext context) {129        testsBegun.add(context.getName());130    }131    @Override132    public void onFinish(ITestContext context) {133        testsEnded.add(context.getName());134    }135    @Override136    public void onStart(ISuite suite) {137        suiteBegun.add(suite.getName());138    }139    @Override140    public void onFinish(ISuite suite) {141        suiteEnded.add(suite.getName());142    }143    @SuppressWarnings("rawtypes")144    @Override145    public void transform(ITestAnnotation annotation, Class testClass, Constructor testCtor,146                    Method testMethod) {147        148        if (testClass != null) {149            xformTest.add("class: " + testClass.getSimpleName());150        } else if (testCtor != null) {151            xformTest.add("ctor: " + testCtor.getName());152        } else {153            xformTest.add("method: " + testMethod.getName());154        }155    }156    @SuppressWarnings("rawtypes")157    // @Override omitted to avoid interface conflict158    public void transform(IConfigurationAnnotation annotation, Class testClass,159                    Constructor testCtor, Method testMethod) {160        161        if (testClass != null) {162            xformConfig.add("class: " + testClass.getSimpleName());163        } else if (testCtor != null) {164            xformConfig.add("ctor: " + testCtor.getName());165        } else {166            xformConfig.add("method: " + testMethod.getName());167        }168    }169    // @Override omitted to avoid interface conflict170    public void transform(IDataProviderAnnotation annotation, Method method) {171        xformProvider.add("method: " + method.getName());172    }173    // @Override omitted to avoid interface conflict174    public void transform(IFactoryAnnotation annotation, Method method) {175        if (method != null) {176            xformFactory.add("method: " + method.getName());177        } else {178            xformFactory.add("ctor: (unknown)");179        }180    }181    @SuppressWarnings("rawtypes")182    // @Override omitted to avoid interface conflict183    public void transform(IListenersAnnotation annotation, Class testClass) {184        xformListeners.add("class: " + testClass.getSimpleName());185    }186    187    @Override188    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {189        interceptor.add(context.getName());190        return methods;191    }192}...Source:Github1649Test.java  
...19public class Github1649Test extends SimpleBaseTest {20  @Test21  public void testHappyFlowForNativeInjectionOnTestMethods() {22    Map<String, List<String>> mapping = Maps.newHashMap();23    mapping.put("m1", Collections.singletonList(Method.class.getName()));24    mapping.put("m2", Collections.singletonList(ITestContext.class.getName()));25    mapping.put("m3", Collections.singletonList(XmlTest.class.getName()));26    mapping.put("m4", Arrays.asList(ITestContext.class.getName(), XmlTest.class.getName()));27    mapping.put("m5", Arrays.asList(XmlTest.class.getName(), ITestContext.class.getName()));28    mapping.put("m6", Arrays.asList(Method.class.getName(), ITestContext.class.getName()));29    mapping.put("m7", Arrays.asList(ITestContext.class.getName(), Method.class.getName()));30    mapping.put("m8", Arrays.asList(Method.class.getName(), XmlTest.class.getName()));31    mapping.put("m9", Arrays.asList(XmlTest.class.getName(), Method.class.getName()));32    mapping.put(33        "m10",34        Arrays.asList(35            Method.class.getName(), XmlTest.class.getName(), ITestContext.class.getName()));36    mapping.put(37        "m11",38        Arrays.asList(39            Method.class.getName(), ITestContext.class.getName(), XmlTest.class.getName()));40    mapping.put(41        "m12",42        Arrays.asList(43            XmlTest.class.getName(), Method.class.getName(), ITestContext.class.getName()));44    mapping.put(45        "m13",46        Arrays.asList(47            XmlTest.class.getName(), ITestContext.class.getName(), Method.class.getName()));48    mapping.put(49        "m14",50        Arrays.asList(51            ITestContext.class.getName(), Method.class.getName(), XmlTest.class.getName()));52    mapping.put(53        "m15",54        Arrays.asList(55            ITestContext.class.getName(), XmlTest.class.getName(), Method.class.getName()));56    TestNG testng = create(HappyPathNativeInjectionTestSample.class);57    Github1649TestListener listener = new Github1649TestListener();58    testng.addListener(listener);59    testng.run();60    assertThat(listener.mapping).containsAllEntriesOf(mapping);61  }62  @Test63  public void testNegativeFlowForNativeInjectionOnTestMethods() {64    Map<String, String> failures = Maps.newHashMap();65    failures.put(66        "m1", "Cannot inject @Test annotated Method [m1] with [interface org.testng.ITestResult].");67    failures.put("m2", "Cannot inject @Test annotated Method [m2] with [int].");68    TestNG testng = create(NegativeNativeInjectionTestSample.class);69    Github1649TestListener listener = new Github1649TestListener();70    testng.addListener(listener);71    testng.run();72    assertThat(listener.failures).containsAllEntriesOf(failures);73  }74  public static class Github1649TestListener extends TestListenerAdapter75      implements IInvokedMethodListener {76    Map<String, List<String>> mapping = Maps.newHashMap();77    Map<String, String> failures = Maps.newHashMap();78    @Override79    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {}80    @Override81    public void onTestFailure(ITestResult testResult) {82      String methodName = testResult.getMethod().getMethodName();83      String raw = testResult.getThrowable().getMessage();84      String actual = raw.split("\n")[1];85      failures.put(methodName, actual);86    }87    @Override88    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {89      String methodName = testResult.getMethod().getMethodName();90      List<String> paramTypes = Lists.newArrayList();91      for (Object parameter : testResult.getParameters()) {92        String value = parameter.getClass().getName();93        if (parameter instanceof ITestContext) {94          value = ITestContext.class.getName();95        }96        paramTypes.add(value);97      }98      mapping.put(methodName, paramTypes);99    }100  }101}...Source:ScreenShotListener.java  
...57     */58    @Override59    public void onTestFailure(ITestResult result) {60    	WaitUtil.mediumWait();61        PageUtil.saveScreenshot(result.getMethod().getTestClass().getName()62                .substring(result.getMethod().getTestClass().getName().lastIndexOf('.') + 1)63                + "." + result.getName(), DriverConfig.getDriver());64    }65    /**66     * On test skipped.67     * @param iTestResult the i test result68     * @see org.testng.ITestListener#onTestSkipped(org.testng.ITestResult)69     */70    @Override71    public void onTestSkipped(ITestResult iTestResult) {72        DriverConfig.setLogString("\033[44;1mSkipped " + System.getProperty(DriverConfig.ENV) + " " + System.getProperty(DriverConfig.BROWSER) + " " + iTestResult.getName(), true);73    }74    /**75     * On test start.76     * @param iTestResult the i test result77     * @see org.testng.ITestListener#onTestStart(org.testng.ITestResult)78     */79    @Override80    public void onTestStart(ITestResult iTestResult) {81    }82    /**83     * On test success.84     * @param iTestResult the i test result85     * @see org.testng.ITestListener#onTestSuccess(org.testng.ITestResult)86     */87    @Override88    public void onTestSuccess(ITestResult iTestResult) {89        DriverConfig.setLogString("\033[42;1mPassed " + System.getProperty(DriverConfig.ENV) + " " + System.getProperty(DriverConfig.BROWSER) + " " + iTestResult.getName(), true);90    }91}...Source:DefaultTestContext.java  
...72    return null;73  }7475  /**76   * @see org.testng.ITestContext#getName()77   */78  public String getName() {79    return null;80  }8182  /**83   * @see org.testng.ITestContext#getOutputDirectory()84   */85  public String getOutputDirectory() {86    return null;87  }8889  /**90   * @see org.testng.ITestContext#getPassedConfigurations()91   */92  public IResultMap getPassedConfigurations() {
...Source:TestNGListeners.java  
...11{12	@Override13	public void onTestStart(ITestResult result)				//it has parameter 'ITestResult', so whatever result comes it will be stored in result object 14	{15		System.out.println("Testcase started and details are"+result.getName());													//this listener gives testcase name of the one failed among 15 testcases16		17	}18	@Override19	public void onTestSuccess(ITestResult result) 20	{21		System.out.println("Testcase passed and details are"+result.getName());22		23	}24	@Override25	public void onTestFailure(ITestResult result) 26	{27		System.out.println("Testcase failed and details are"+result.getName());28		29	}30	@Override31	public void onTestSkipped(ITestResult result) 32	{33		34		System.out.println("Testcase skipped and details are"+result.getName());35	}36	@Override37	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {38		39		40	}41	@Override42	public void onStart(ITestContext context) {43		44		45	}46	@Override47	public void onFinish(ITestContext context) {48		...Source:CustomListeners.java  
...4import org.testng.ITestResult;5public class CustomListeners implements ITestListener{6	//This belongs to ITestListener and will execute before starting of Test set/batch7	public void onStart(ITestContext arg) {8		System.out.println("Starts Test Execution......"+arg.getName());9	}10	11	//This belongs to ITestListener and will execute after starting of Test set/batch12	public void onFinish(ITestContext arg) {13		System.out.println("Finish Test Execution......"+arg.getName());14	}15	16	//This belongs to ITestListener and will execute after the main test starts i.e., @Test17	public void onTestStart(ITestResult arg0) {18		System.out.println("Starts test......"+arg0.getName());19	}20	21	//This belongs to ITestListener and will execute when a test is skipped22	public void onTestSkipped(ITestResult arg0) {23		System.out.println("Skipped test......"+arg0.getName());24	}25	26	//This belongs to ITestListener and will execute when a test is passed27	public void onTestSuccess(ITestResult arg0) {28		System.out.println("Passed test......"+arg0.getName());29	}30	31	//This belongs to ITestListener and will execute when a test is failed32	public void onTestFailure(ITestResult arg0) {33		System.out.println("Failed test......"+arg0.getName());34	}35	36	//Not so important.. ignore this as of now37	public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {38		//as ITestListener is interface, we need to address all the methods39	}40	41}...Source:ListenerTest.java  
...67public class ListenerTest implements ITestListener {8	//   "ITestListener" is the interface9		public void onFinish(ITestContext Result) {10			System.out.println("The name of the testcase finished :" + Result.getName());11		}12		public void onStart(ITestContext Result) {13			System.out.println("The name of the testcase start :" + Result.getName());14		}15		public void onTestFailedButWithinSuccessPercentage(ITestResult Result) {16			System.out.println("The name of the testcase SuccessPercentage is :" + Result.getName());17		}18		// When Test case get failed, this method is called.19		public void onTestFailure(ITestResult Result) {20			System.out.println("The name of the testcase failed is :" + Result.getName());21		}22		// When Test case get Skipped, this method is called.23		public void onTestSkipped(ITestResult Result) {24			System.out.println("The name of the testcase Skipped is :" + Result.getName());25		}26		// When Test case get Started, this method is called.27		public void onTestStart(ITestResult Result) {28			System.out.println(Result.getName() + " test case started");29		}30		// When Test case get passed, this method is called.31		public void onTestSuccess(ITestResult Result) {32			System.out.println("The name of the testcase passed is :" + Result.getName());33		}3435	}36
...Source:Listeners.java  
...14    @Override15    public void onTestFailure(ITestResult iTestResult) {16        //Screenshot code17        //response if API is failed18        System.out.println("This is my Listener for when their is a Failed Test; the test that was failed is " + iTestResult.getName());19    }20    @Override21    public void onTestSkipped(ITestResult iTestResult) {22    }23    @Override24    public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {25    }26    @Override27    public void onStart(ITestContext iTestContext) {28    }29    @Override30    public void onFinish(ITestContext iTestContext) {31    }32}...getName
Using AI Code Generation
1String testName = context.getName();2ITestNGMethod[] passedTests = context.getPassedTests().getAllMethods();3ITestNGMethod[] failedTests = context.getFailedTests().getAllMethods();4ITestNGMethod[] skippedTests = context.getSkippedTests().getAllMethods();5ITestNGMethod[] excludedTests = context.getExcludedMethods();6String outputDirectory = context.getOutputDirectory();7Date startDate = context.getStartDate();8Date endDate = context.getEndDate();9Set<ITestResult> passedTests = context.getPassedTests().getAllResults();10Set<ITestResult> failedTests = context.getFailedTests().getAllResults();11Set<ITestResult> skippedTests = context.getSkippedTests().getAllResults();12Set<ITestResult> excludedTests = context.getExcludedMethods();13Set<ITestResult> passedConfigurations = context.getPassedConfigurations().getAllResults();14Set<ITestResult> failedConfigurations = context.getFailedConfigurations().getAllResults();15Set<ITestResult> skippedConfigurations = context.getSkippedConfigurations().getAllResults();getName
Using AI Code Generation
1String suiteName = context.getName();2IResultMap passedTests = context.getPassedTests();3IResultMap failedTests = context.getFailedTests();4IResultMap skippedTests = context.getSkippedTests();5IResultMap passedConfigurations = context.getPassedConfigurations();6IResultMap failedConfigurations = context.getFailedConfigurations();7IResultMap skippedConfigurations = context.getSkippedConfigurations();8String outputDirectory = context.getOutputDirectory();9String outputDirectory = context.getOutputDirectory();10ITestNGMethod[] allTestMethods = context.getAllTestMethods();11ISuite suite = context.getSuite();12IResultMap failedButWithinSuccessPercentageTests = context.getFailedButWithinSuccessPercentageTests();13String host = context.getHost();14Date startDate = context.getStartDate();15Date endDate = context.getEndDate();16IResultMap failedTests = context.getFailedTests();17IResultMap passedTests = context.getPassedTests();18IResultMap skippedTests = context.getSkippedTests();getName
Using AI Code Generation
1public void test(ITestContext context) {2    String name = context.getName();3    System.out.println("name = " + name);4}5public void test(ITestContext context) {6    String outputDirectory = context.getOutputDirectory();7    System.out.println("outputDirectory = " + outputDirectory);8}9public void test(ITestContext context) {10    String outputDirectory = context.getOutputDirectory();11    System.out.println("outputDirectory = " + outputDirectory);12}13public void test(ITestContext context) {14    IResultMap passedTests = context.getPassedTests();15    System.out.println("passedTests = " + passedTests);16}17public void test(ITestContext context) {18    IResultMap passedTests = context.getPassedTests();19    System.out.println("passedTests = " + passedTests);20}21public void test(ITestContext context) {22    IResultMap passedTests = context.getPassedTests();23    System.out.println("passedTests = " + passedTests);24}25public void test(ITestContext context) {26    IResultMap passedTests = context.getPassedTests();27    System.out.println("passedTests = " + passedTests);28}29public void test(ITestContext context) {30    IResultMap passedTests = context.getPassedTests();31    System.out.println("passedTests = " + passedTests);32}33public void test(ITestContext context) {34    IResultMap passedTests = context.getPassedTests();35    System.out.println("passedTests = " + passedTests);36}37public void test(ITestContext context) {38    IResultMap passedTests = context.getPassedTests();getName
Using AI Code Generation
1ITestContext ctx = Reporter.getCurrentTestResult().getTestContext();2String testName = ctx.getName();3String testName = Reporter.getCurrentTestResult().getName();4String testName = Reporter.getCurrentTestResult().getTestContext().getName();5String testName = Reporter.getCurrentTestResult().getTestContext().getCurrentXmlTest().getName();6String testName = Reporter.getCurrentTestResult().getTestContext().getCurrentXmlTest().getSuite().getName();7String testName = Reporter.getCurrentTestResult().getTestContext().getCurrentXmlTest().getSuite().getName();8String testName = Reporter.getCurrentTestResult().getTestContext().getCurrentXmlTest().getSuite().getName();9String testName = Reporter.getCurrentTestResult().getTestContext().getCurrentXmlTest().getSuite().getName();getName
Using AI Code Generation
1import org.testng.ITestContext;2public class TestNGContext {3   public void getTestName(ITestContext context) {4      System.out.println("Test Name: " + context.getName());5   }6}7import org.testng.ITestContext;8public class TestNGContext {9   public void getPassedTests(ITestContext context) {10      System.out.println("Passed Tests: " + context.getPassedTests());11   }12}13import org.testng.ITestContext;14public class TestNGContext {15   public void getFailedTests(ITestContext context) {16      System.out.println("Failed Tests: " + context.getFailedTests());17   }18}19import org.testng.ITestContext;20public class TestNGContext {21   public void getSkippedTests(ITestContext context) {22      System.out.println("Skipped Tests: " + context.getSkippedTests());23   }24}25import org.testng.ITestContext;26public class TestNGContext {27   public void getExcludedMethods(ITestContext context) {28      System.out.println("Excluded Methods: " + context.getExcludedMethods());29   }30}31import org.testng.ITestContext;32public class TestNGContext {33   public void getOutputDirectory(ITestContext context) {34      System.out.println("Output Directory: " + context.getOutputDirectory());35   }36}37import org.testng.ITestContext;38public class TestNGContext {39   public void getStartDate(ITestContext context) {40      System.out.println("Start Date: " + context.getStartDate());41   }42}43import org.testng.ITestContext;44public class TestNGContext {45   public void getEndDate(ITestContext context) {46      System.out.println("End Date: " + context.getEndDate());47   }48}49import org.testng.ITestContext;50public class TestNGContext {51   public void getSuite(ITTestNG 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!!
