Best Testng code snippet using org.testng.TestNG.getAnnotationTransformer
Source:TestNG.java
...666 }667 }668 669 private void initializeAnnotationFinders() {670 m_javadocAnnotationFinder= new JDK14AnnotationFinder(getAnnotationTransformer()); 671 if (null != m_sourceDirs) {672 m_javadocAnnotationFinder.addSourceDirs(m_sourceDirs);673 }674 if (!VersionInfo.IS_JDK14) {675 m_jdkAnnotationFinder= ClassHelper.createJdkAnnotationFinder(getAnnotationTransformer());676 }677 }678 679 /**680 * Run TestNG.681 */682 public void run() {683 initializeListeners();684 initializeCommandLineSuites();685 initializeCommandLineSuitesParams();686 initializeCommandLineSuitesGroups();687 688 List<ISuite> suiteRunners = null;689 690 //691 // Slave mode692 //693 if (m_slavefileName != null) {694 SuiteSlave slave = new SuiteSlave( m_slavefileName, this );695 slave.waitForSuites();696 }697 698 //699 // Regular mode700 //701 else if (m_masterfileName == null) {702 suiteRunners = runSuitesLocally();703 }704 705 //706 // Master mode707 //708 else {709 SuiteDispatcher dispatcher = new SuiteDispatcher( m_masterfileName);710 suiteRunners = dispatcher.dispatch(m_suites, getOutputDirectory(),711 m_javadocAnnotationFinder, m_jdkAnnotationFinder, getTestListeners());712 }713 714 initializeAnnotationFinders();715 if(null != suiteRunners) {716 generateReports(suiteRunners);717 }718 719 if(!m_hasTests) {720 setStatus(HAS_NO_TEST);721 if (TestRunner.getVerbose() > 1) {722 System.err.println("[TestNG] No tests found. Nothing was run");723 }724 }725 }726 727 private void generateReports(List<ISuite> suiteRunners) {728 for (IReporter reporter : m_reporters) {729 try {730 reporter.generateReport(m_suites, suiteRunners, m_outputDir);731 }732 catch(Exception ex) {733 System.err.println("[TestNG] Reporter " + reporter + " failed");734 ex.printStackTrace(System.err);735 }736 }737 }738 /**739 * This needs to be public for maven2, for now..At least740 * until an alternative mechanism is found.741 * @return742 */743 public List<ISuite> runSuitesLocally() {744 List<ISuite> result = new ArrayList<ISuite>();745 746 if (m_verbose > 0) {747 StringBuffer allFiles = new StringBuffer();748 for (XmlSuite s : m_suites) {749 allFiles.append(" ").append(s.getFileName() != null ? s.getFileName() : getDefaultSuiteName()).append('\n');750 }751 Utils.log("Parser", 0, "Running:\n" + allFiles.toString());752 }753 if (m_suites.size() > 0) {754 for (XmlSuite xmlSuite : m_suites) {755 xmlSuite.setDefaultAnnotations(m_defaultAnnotations.toString());756 757 if (null != m_isJUnit) {758 xmlSuite.setJUnit(m_isJUnit);759 }760 761 //762 // Install the listeners763 //764 for (String listenerName : xmlSuite.getListeners()) {765 Class<?> listenerClass = ClassHelper.forName(listenerName);766 Object listener = ClassHelper.newInstance(listenerClass);767 addListener(listener);768 }769 770 // If the skip flag was invoked on the command line, it771 // takes precedence772 if (null != m_skipFailedInvocationCounts) {773 xmlSuite.setSkipFailedInvocationCounts(m_skipFailedInvocationCounts);774 }775 else {776 m_skipFailedInvocationCounts = xmlSuite.skipFailedInvocationCounts();777 }778 779 if (xmlSuite.getVerbose() == null) {780 xmlSuite.setVerbose(m_verbose);781 }782 783 result.add(createAndRunSuiteRunners(xmlSuite));784 }785 }786 else {787 setStatus(HAS_NO_TEST);788 System.err.println("[ERROR]: No test suite found. Nothing to run");789 }790 791 //792 // Generate the suites report793 //794 return result;795 }796 protected SuiteRunner createAndRunSuiteRunners(XmlSuite xmlSuite) {797 initializeAnnotationFinders();798 SuiteRunner result = new SuiteRunner(xmlSuite, 799 m_outputDir, 800 m_testRunnerFactory, 801 m_useDefaultListeners, 802 new IAnnotationFinder[] {803 m_javadocAnnotationFinder, 804 m_jdkAnnotationFinder805 },806 m_objectFactory,807 m_methodInterceptor,808 m_invokedMethodListeners);809 result.setSkipFailedInvocationCounts(m_skipFailedInvocationCounts);810 for (ISuiteListener isl : m_suiteListeners) {811 result.addListener(isl);812 }813 814 result.setTestListeners(m_testListeners);815 result.run();816 return result;817 }818 /**819 * The TestNG entry point for command line execution. 820 *821 * @param argv the TestNG command line parameters.822 */823 public static void main(String[] argv) {824 TestNG testng = privateMain(argv, null);825 System.exit(testng.getStatus());826 }827 828 /**829 * <B>Note</B>: this method is not part of the public API and is meant for internal usage only.830 * TODO JavaDoc.831 *832 * @param argv833 * @param listener834 * @return 835 */836 /**837 * @param argv838 * @param listener839 * @return840 */841 public static TestNG privateMain(String[] argv, ITestListener listener) {842 Map arguments= checkConditions(TestNGCommandLineArgs.parseCommandLine(argv));843 844 TestNG result = new TestNG();845 if (null != listener) {846 result.addListener(listener);847 }848 result.configure(arguments);849 try {850 result.run();851 }852 catch(TestNGException ex) {853 if (TestRunner.getVerbose() > 1) {854 ex.printStackTrace(System.out);855 }856 else {857 System.err.println("[ERROR]: " + ex.getMessage());858 }859 result.setStatus(HAS_FAILURE);860 }861 return result;862 }863 /**864 * Configure the TestNG instance by reading the settings provided in the map.865 * 866 * @param cmdLineArgs map of settings867 * @see TestNGCommandLineArgs for setting keys868 */869 @SuppressWarnings({"unchecked"})870 public void configure(Map cmdLineArgs) {871 {872 Integer verbose = (Integer) cmdLineArgs.get(TestNGCommandLineArgs.LOG);873 if (null != verbose) {874 setVerbose(verbose.intValue());875 }876 }877 878 setOutputDirectory((String) cmdLineArgs.get(TestNGCommandLineArgs.OUTDIR_COMMAND_OPT));879 setSourcePath((String) cmdLineArgs.get(TestNGCommandLineArgs.SRC_COMMAND_OPT));880 setAnnotations(((AnnotationTypeEnum) cmdLineArgs.get(TestNGCommandLineArgs.ANNOTATIONS_COMMAND_OPT)));881 List<Class> testClasses = (List<Class>) cmdLineArgs.get(TestNGCommandLineArgs.TESTCLASS_COMMAND_OPT);882 if (null != testClasses) {883 Class[] classes = (Class[]) testClasses.toArray(new Class[testClasses.size()]);884 setTestClasses(classes);885 }886 List<String> testNgXml = (List<String>) cmdLineArgs.get(TestNGCommandLineArgs.SUITE_DEF_OPT);887 if (null != testNgXml) {888 setTestSuites(testNgXml);889 }890 891 String useDefaultListeners = (String) cmdLineArgs.get(TestNGCommandLineArgs.USE_DEFAULT_LISTENERS);892 if (null != useDefaultListeners) {893 setUseDefaultListeners("true".equalsIgnoreCase(useDefaultListeners));894 }895 896 setGroups((String) cmdLineArgs.get(TestNGCommandLineArgs.GROUPS_COMMAND_OPT));897 setExcludedGroups((String) cmdLineArgs.get(TestNGCommandLineArgs.EXCLUDED_GROUPS_COMMAND_OPT)); 898 setTestJar((String) cmdLineArgs.get(TestNGCommandLineArgs.TESTJAR_COMMAND_OPT));899 setJUnit((Boolean) cmdLineArgs.get(TestNGCommandLineArgs.JUNIT_DEF_OPT));900 setMaster( (String)cmdLineArgs.get(TestNGCommandLineArgs.MASTER_OPT));901 setSlave( (String)cmdLineArgs.get(TestNGCommandLineArgs.SLAVE_OPT));902 setSkipFailedInvocationCounts(903 (Boolean) cmdLineArgs.get(904 TestNGCommandLineArgs.SKIP_FAILED_INVOCATION_COUNT_OPT));905 906 String parallelMode = (String) cmdLineArgs.get(TestNGCommandLineArgs.PARALLEL_MODE);907 if (parallelMode != null) {908 setParallel(parallelMode);909 }910 911 String threadCount = (String) cmdLineArgs.get(TestNGCommandLineArgs.THREAD_COUNT);912 if (threadCount != null) {913 setThreadCount(Integer.parseInt(threadCount));914 }915 916 String defaultSuiteName = (String) cmdLineArgs.get(TestNGCommandLineArgs.SUITE_NAME_OPT);917 if (defaultSuiteName != null) {918 setDefaultSuiteName(defaultSuiteName);919 }920 String defaultTestName = (String) cmdLineArgs.get(TestNGCommandLineArgs.TEST_NAME_OPT);921 if (defaultTestName != null) {922 setDefaultTestName(defaultTestName);923 }924 List<Class> listenerClasses = (List<Class>) cmdLineArgs.get(TestNGCommandLineArgs.LISTENER_COMMAND_OPT);925 if (null != listenerClasses) {926 setListenerClasses(listenerClasses);927 }928 929 Class objectFactory = (Class) cmdLineArgs.get(TestNGCommandLineArgs.OBJECT_FACTORY_COMMAND_OPT);930 if(null != objectFactory) {931 setObjectFactory(objectFactory);932 }933 Class runnerFactory = (Class) cmdLineArgs.get(TestNGCommandLineArgs.TESTRUNNER_FACTORY_COMMAND_OPT);934 if (null != runnerFactory) {935 setTestRunnerFactoryClass(runnerFactory);936 }937 List<ReporterConfig> reporterConfigs =938 (List<ReporterConfig>) cmdLineArgs.get(TestNGCommandLineArgs.REPORTERS_LIST);939 if (reporterConfigs != null) {940 for (ReporterConfig reporterConfig : reporterConfigs) {941 addReporter(reporterConfig);942 }943 }944 }945 private void setSkipFailedInvocationCounts(Boolean skip) {946 m_skipFailedInvocationCounts = skip;947 }948 private void addReporter(ReporterConfig reporterConfig) {949 Object instance = reporterConfig.newReporterInstance();950 if (instance != null) {951 addListener(instance);952 } else {953 LOGGER.warn("Could not find reporte class : " + reporterConfig.getClassName());954 }955 }956 /**957 * Specify if this run should be in Master-Slave mode as Master958 * 959 * @param fileName remote.properties path960 */961 public void setMaster(String fileName) {962 m_masterfileName = fileName;963 }964 965 /**966 * Specify if this run should be in Master-Slave mode as slave967 * 968 * @param fileName remote.properties path969 */970 public void setSlave(String fileName) {971 m_slavefileName = fileName;972 }973 974 /**975 * Specify if this run should be made in JUnit mode976 * 977 * @param isJUnit978 */979 public void setJUnit(Boolean isJUnit) {980 m_isJUnit = isJUnit;981 }982 983 /**984 * @deprecated The TestNG version is now established at load time. This 985 * method is not required anymore and is now a no-op. 986 */987 @Deprecated988 public static void setTestNGVersion() {989 LOGGER.info("setTestNGVersion has been deprecated.");990 }991 992 /**993 * Returns true if this is the JDK 1.4 JAR version of TestNG, false otherwise.994 *995 * @return true if this is the JDK 1.4 JAR version of TestNG, false otherwise.996 */997 public static boolean isJdk14() {998 return VersionInfo.IS_JDK14;999 }1000 /**1001 * Checks TestNG preconditions. For example, this method makes sure that if this is the1002 * JDK 1.4 version of TestNG, a source directory has been specified. This method calls1003 * System.exit(-1) or throws an exception if the preconditions are not satisfied.1004 * 1005 * @param params the parsed command line parameters.1006 */1007 @SuppressWarnings({"unchecked"})1008 protected static Map checkConditions(Map params) {1009 // TODO CQ document why sometimes we throw exceptions and sometimes we exit. 1010 List<String> testClasses = (List<String>) params.get(TestNGCommandLineArgs.TESTCLASS_COMMAND_OPT);1011 List<String> testNgXml = (List<String>) params.get(TestNGCommandLineArgs.SUITE_DEF_OPT);1012 Object testJar = params.get(TestNGCommandLineArgs.TESTJAR_COMMAND_OPT);1013 Object slave = params.get(TestNGCommandLineArgs.SLAVE_OPT);1014 if (testClasses == null && testNgXml == null && slave == null && testJar == null) {1015 System.err.println("You need to specify at least one testng.xml or one class");1016 usage();1017 System.exit(-1);1018 }1019 if (VersionInfo.IS_JDK14) {1020 String srcPath = (String) params.get(TestNGCommandLineArgs.SRC_COMMAND_OPT);1021 if ((null == srcPath) || "".equals(srcPath)) {1022 throw new TestNGException("No sourcedir was specified");1023 }1024 }1025 1026 String groups = (String) params.get(TestNGCommandLineArgs.GROUPS_COMMAND_OPT);1027 String excludedGroups = (String) params.get(TestNGCommandLineArgs.EXCLUDED_GROUPS_COMMAND_OPT);1028 1029 if (testJar == null &&1030 (null != groups || null != excludedGroups) && null == testClasses) {1031 throw new TestNGException("Groups option should be used with testclass option");1032 }1033 1034 // -slave & -master can't be set together1035 if (params.containsKey(TestNGCommandLineArgs.SLAVE_OPT) && 1036 params.containsKey(TestNGCommandLineArgs.MASTER_OPT)) {1037 throw new TestNGException(TestNGCommandLineArgs.SLAVE_OPT + " can't be combined with " +1038 TestNGCommandLineArgs.MASTER_OPT);1039 }1040 1041 return params;1042 }1043 /**1044 * @return true if at least one test failed.1045 */1046 public boolean hasFailure() {1047 return (getStatus() & HAS_FAILURE) == HAS_FAILURE;1048 }1049 /**1050 * @return true if at least one test failed within success percentage.1051 */1052 public boolean hasFailureWithinSuccessPercentage() {1053 return (getStatus() & HAS_FSP) == HAS_FSP;1054 }1055 /**1056 * @return true if at least one test was skipped.1057 */1058 public boolean hasSkip() {1059 return (getStatus() & HAS_SKIPPED) == HAS_SKIPPED;1060 }1061 1062 /**1063 * Prints the usage message to System.out. This message describes all the command line1064 * options.1065 */1066 public static void usage() {1067 TestNGCommandLineArgs.usage();1068 }1069 1070 static void exitWithError(String msg) {1071 System.err.println(msg);1072 usage();1073 System.exit(1);1074 }1075 public String getOutputDirectory() {1076 return m_outputDir;1077 }1078 1079 public IAnnotationTransformer getAnnotationTransformer() {1080 return m_annotationTransformer;1081 }1082 1083 public boolean getSkipFailedInvocationCounts() {1084 return m_skipFailedInvocationCounts;1085 }1086 1087 public void setSkipFailedInvocationCounts(boolean skip) {1088 m_skipFailedInvocationCounts = skip;1089 }1090 1091 public void setAnnotationTransformer(IAnnotationTransformer t) {1092 m_annotationTransformer = t;1093 }...
getAnnotationTransformer
Using AI Code Generation
1@TestNG testNG = new TestNG();2testNG.setAnnotationTransformer(new AnnotationTransformer() {3 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {4 annotation.setRetryAnalyzer(RetryAnalyzer.class);5 }6});7testNG.setTestClasses(new Class[] { TestClass.class });8testNG.run();9@Test(retryAnalyzer = RetryAnalyzer.class)10public void testMethod() {11}12@RetryAnalyzer(RetryAnalyzer.class)13public void testMethod() {14}15@RetryAnalyzer(value = RetryAnalyzer.class)16public void testMethod() {17}18@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = false)19public void testMethod() {20}21@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = true)22public void testMethod() {23}24@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = false)25public void testMethod() {26}27@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = true)28public void testMethod() {29}30@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = false)31public void testMethod() {32}33@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = true)34public void testMethod() {35}36@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = false)37public void testMethod() {38}39@RetryAnalyzer(value = RetryAnalyzer.class, inheritRetryAnalyzer = true)40public void testMethod()
getAnnotationTransformer
Using AI Code Generation
1package com.test;2import java.lang.reflect.Constructor;3import java.lang.reflect.Method;4import org.testng.IAnnotationTransformer;5import org.testng.annotations.ITestAnnotation;6public class AnnotationTransformer implements IAnnotationTransformer {7 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {8 annotation.setRetryAnalyzer(RetryAnalyzer.class);9 }10}11package com.test;12import org.testng.IRetryAnalyzer;13import org.testng.ITestResult;14public class RetryAnalyzer implements IRetryAnalyzer {15 private int retryCount = 0;16 private static final int maxRetryCount = 1;17 public boolean retry(ITestResult result) {18 if (retryCount < maxRetryCount) {19 System.out.println("Retrying test " + result.getName() + " with status "20 + getResultStatusName(result.getStatus()) + " for the " + (retryCount + 1) + " time(s).");21 retryCount++;22 return true;23 }24 return false;25 }26 public String getResultStatusName(int status) {27 String resultName = null;28 if (status == 1)29 resultName = "SUCCESS";30 if (status == 2)31 resultName = "FAILURE";32 if (status == 3)33 resultName = "SKIP";34 return resultName;35 }36}37package com.test;38import org.testng.Assert;39import org.testng.annotations.Test;40public class TestClass {41 public void testMethod1() {42 Assert.assertTrue(true);43 }44 public void testMethod2() {45 Assert.assertTrue(false);46 }47 public void testMethod3() {48 Assert.assertTrue(false);49 }50}51package com.test;52import org.testng.annotations.Test;53public class TestClass {54 @Test(retryAnalyzer = RetryAnalyzer.class)55 public void testMethod1() {56 Assert.assertTrue(true);57 }58 @Test(retryAnalyzer = RetryAnalyzer.class)59 public void testMethod2() {60 Assert.assertTrue(false);61 }62 @Test(retryAnalyzer = RetryAnalyzer.class)63 public void testMethod3() {64 Assert.assertTrue(false);65 }66}67package com.test;68import org.testng.Assert
getAnnotationTransformer
Using AI Code Generation
1public void testGetAnnotationTransformer() {2 TestNG testng = new TestNG();3 IAnnotationTransformer transformer = new IAnnotationTransformer() {4 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {5 annotation.setRetryAnalyzer(RetryAnalyzer.class);6 }7 };8 testng.setAnnotationTransformer(transformer);9 testng.setTestClasses(new Class[] { TestClassSample.class });10 testng.run();11}12@RetryAnalyzer(RetryAnalyzer.class)13public class TestClassSample {14 public void testMethod() {15 System.out.println("This is a test method");16 }17}18public class RetryAnalyzer implements IRetryAnalyzer {19 private int retryCount = 0;20 private static final int maxRetryCount = 2;21 public boolean retry(ITestResult result) {22 if (retryCount < maxRetryCount) {23 System.out.println("Retrying test " + result.getName() + " with status "24 + getResultStatusName(result.getStatus()) + " for the " + (retryCount+1) + " time(s).");25 retryCount++;26 return true;27 }28 return false;29 }30 public String getResultStatusName(int status) {31 String resultName = null;32 if(status == 1)33 resultName = "SUCCESS";34 if(status == 2)35 resultName = "FAILURE";36 if(status == 3)37 resultName = "SKIP";38 return resultName;39 }40}
getAnnotationTransformer
Using AI Code Generation
1package com.test;2import org.testng.IAnnotationTransformer;3import org.testng.annotations.ITestAnnotation;4import java.lang.reflect.Constructor;5import java.lang.reflect.Method;6public class AnnotationTransformer implements IAnnotationTransformer {7 public void transform(ITestAnnotation iTestAnnotation, Class aClass, Constructor constructor, Method method) {8 iTestAnnotation.setRetryAnalyzer(RetryAnalyzer.class);9 }10}11package com.test;12import org.testng.IRetryAnalyzer;13import org.testng.ITestResult;14public class RetryAnalyzer implements IRetryAnalyzer {15 private int retryCount = 0;16 private static final int maxRetryCount = 1;17 public boolean retry(ITestResult iTestResult) {18 if (retryCount < maxRetryCount) {19 System.out.println("Retrying test " + iTestResult.getName() + " with status "20 + getResultStatusName(iTestResult.getStatus()) + " for the " + (retryCount+1) + " time(s).");21 retryCount++;22 return true;23 }24 return false;25 }26 public String getResultStatusName(int status) {27 String resultName = null;28 if(status==1)29 resultName = "SUCCESS";30 if(status==2)31 resultName = "FAILURE";32 if(status==3)33 resultName = "SKIP";34 return resultName;35 }36}37package com.test;38import org.testng.Assert;39import org.testng.annotations.Test;40public class TestNGRetryFailedTestCases {41 public void testMethod1() {42 System.out.println("TestNGRetryFailedTestCases -> This is testMethod1");43 }44 public void testMethod2() {45 System.out.println("TestNGRetryFailedTestCases -> This is testMethod2");46 Assert.assertTrue(false);47 }48 public void testMethod3() {49 System.out.println("TestNGRetryFailedTestCases -> This is testMethod3");50 Assert.assertTrue(false);51 }52}53package com.test;54import org.testng.Assert;55import org.testng.annotations.Test;56public class TestNGRetryFailedTestCases {57 public void testMethod1() {58 System.out.println("TestNGRetryFailedTestCases -> This is testMethod
getAnnotationTransformer
Using AI Code Generation
1public class AnnotationTransformer implements IAnnotationTransformer {2 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {3 annotation.setRetryAnalyzer(RetryAnalyzer.class);4 }5}6public class RetryAnalyzer implements IRetryAnalyzer {7 private int retryCount = 0;8 private static final int maxRetryCount = 1;9 public boolean retry(ITestResult result) {10 if (retryCount < maxRetryCount) {11 retryCount++;12 return true;13 }14 return false;15 }16}17TestNG testNG = new TestNG();18testNG.setTestClasses(new Class[]{Test1.class, Test2.class});19testNG.getAnnotationTransformer().transform(null, null, null, null);20testNG.run();21public class AnnotationTransformer implements IAnnotationTransformer {22 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {23 annotation.setRetryAnalyzer(RetryAnalyzer.class);24 }25}26public class RetryAnalyzer implements IRetryAnalyzer {27 private int retryCount = 0;28 private static final int maxRetryCount = 1;29 public boolean retry(ITestResult result) {30 if (retryCount < maxRetryCount) {31 retryCount++;32 return true;33 }34 return false;35 }36}37TestNG testNG = new TestNG();38testNG.setTestClasses(new Class[]{Test1.class, Test2.class});39testNG.getAnnotationTransformer().transform(null, null, null, null);40testNG.run();
getAnnotationTransformer
Using AI Code Generation
1public class TestNGFailedListener implements IAnnotationTransformer {2 private static final Logger LOGGER = Logger.getLogger(TestNGFailedListener.class);3 private static final String TESTNG_FAILED_XML = "testng-failed.xml";4 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {5 if (testMethod != null) {6 LOGGER.info("test method name: " + testMethod.getName());7 List<String> failedTests = new ArrayList<>();8 failedTests.add(testMethod.getName());9 try {10 FileUtils.writeLines(new File(TESTNG_FAILED_XML), failedTests);11 } catch (IOException e) {12 LOGGER.error("Error writing to testng-failed.xml file");13 }14 }15 }16}17public class TestNGFailedListener implements IAnnotationTransformer {18 private static final Logger LOGGER = Logger.getLogger(TestNGFailedListener.class);19 private static final String TESTNG_FAILED_XML = "testng-failed.xml";20 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {21 if (testMethod != null) {22 LOGGER.info("test method name: " + testMethod.getName());23 List<String> failedTests = new ArrayList<>();24 try {25 failedTests = FileUtils.readLines(new File(TESTNG_FAILED_XML));26 } catch (IOException e) {27 LOGGER.error("Error reading from testng-failed.xml file");28 }29 failedTests.add(testMethod.getName());30 try {31 FileUtils.writeLines(new File(TESTNG_FAILED_XML), failedTests);32 } catch (IOException e) {33 LOGGER.error("Error writing to testng-failed.xml file");34 }35 }36 }37}
getAnnotationTransformer
Using AI Code Generation
1public class TestNGCustomAnnotationTransformer {2 public static void main(String[] args) {3 TestNG testNG = new TestNG();4 testNG.setTestClasses(new Class[] { TestClassSample.class });5 testNG.setAnnotationTransformer(new IAnnotationTransformer() {6 public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor,7 Method testMethod) {8 if (testMethod.getName().contains("ignore")) {9 annotation.setEnabled(false);10 }11 }12 });13 testNG.run();14 }15}16public class TestClassSample {17 public void testMethod1() {18 System.out.println("testMethod1");19 }20 public void testMethod2() {21 System.out.println("testMethod2");22 }23 public void testMethod3_ignore() {24 System.out.println("testMethod3_ignore");25 }26}
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!!