Best Testng code snippet using org.testng.Interface I.getRealClass
Source:AbstractChainedListener.java
...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 @Override...
Source:TestngListener.java
...110 Date date = new Date();111 SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_hh_mm_ss");112 String sdate = sdf.format(date);113 114 String sClass=result.getTestClass().getRealClass().toString();115 sClass= sClass.replace("class ", "");116 117 String sPackage=result.getTestClass().getRealClass().getPackage().toString();118 sPackage = sPackage.replace("package ", "");119 120 String sImage = sClass.replace(sPackage+".","");121 sImage = sImage+"_"+result.getName().toString();122 123 Object obj=result.getInstance();124 BaseLib baseLib = (BaseLib)obj;125 qrLog.error("TEST STATUS = FAILED"+" ");126 qrLog.info("___________________________________________________");127 qrLog.info(" ");128 File imgFile = ((TakesScreenshot) baseLib.driver).getScreenshotAs(OutputType.FILE);129 System.out.println(imgFile.getAbsolutePath());130 try131 {...
Source:MethodInheritance.java
...37 private static final Comparator<ITestNGMethod> COMPARATOR = new Comparator<ITestNGMethod>() {38 @Override39 public int compare(ITestNGMethod o1, ITestNGMethod o2) {40 int result = -2;41 Class<?> thisClass = o1.getRealClass();42 Class<?> otherClass = o2.getRealClass();43 if (thisClass.isAssignableFrom(otherClass)) {44 result = -1;45 } else if (otherClass.isAssignableFrom(thisClass)) {46 result = 1;47 } else if (o1.equals(o2)) {48 result = 0;49 }50 return result;51 }52 };53 /**54 * Look in map for a class that is a superclass of methodClass55 */56 private static List<ITestNGMethod> findMethodListSuperClass(Map<Class, List<ITestNGMethod>> map,57 Class< ? extends ITestNGMethod> methodClass)58 {59 for (Map.Entry<Class, List<ITestNGMethod>> entry : map.entrySet()) {60 if (entry.getKey().isAssignableFrom(methodClass)) {61 return entry.getValue();62 }63 }64 return null;65 }66 /**67 * Look in map for a class that is a subclass of methodClass68 */69 private static Class findSubClass(Map<Class, List<ITestNGMethod>> map,70 Class< ? extends ITestNGMethod> methodClass)71 {72 for (Class cls : map.keySet()) {73 if (methodClass.isAssignableFrom(cls)) {74 return cls;75 }76 }77 return null;78 }79 /**80 * Fix the methodsDependedUpon to make sure that @Configuration methods81 * respect inheritance (before methods are invoked in the order Base first82 * and after methods are invoked in the order Child first)83 *84 * @param methods the list of methods85 * @param before true if we are handling a before method (meaning, the methods86 * need to be sorted base class first and subclass last). false otherwise (subclass87 * methods first, base classes last).88 */89 public static void fixMethodInheritance(ITestNGMethod[] methods, boolean before) {90 // Map of classes -> List of methods that belong to this class or same hierarchy91 Map<Class, List<ITestNGMethod>> map = Maps.newHashMap();92 //93 // Put the list of methods in their hierarchy buckets94 //95 for (ITestNGMethod method : methods) {96 Class< ? extends ITestNGMethod> methodClass = method.getRealClass();97 List<ITestNGMethod> l = findMethodListSuperClass(map, methodClass);98 if (null != l) {99 l.add(method);100 }101 else {102 Class subClass = findSubClass(map, methodClass);103 if (null != subClass) {104 l = map.get(subClass);105 l.add(method);106 map.remove(subClass);107 map.put(methodClass, l);108 }109 else {110 l = Lists.newArrayList();111 l.add(method);112 map.put(methodClass, l);113 }114 }115 }116 //117 // Each bucket that has a list bigger than one element gets sorted118 //119 for (List<ITestNGMethod> l : map.values()) {120 if (l.size() > 1) {121 // Sort them122 sortMethodsByInheritance(l, before);123 /*124 * Set methodDependedUpon accordingly125 * E.g. Base class can have multiple @BeforeClass methods. Need to ensure126 * that @BeforeClass methods in derived class depend on all @BeforeClass methods127 * of base class. Vice versa for @AfterXXX methods128 */129 for (int i = 0; i < l.size() - 1; i++) {130 ITestNGMethod m1 = l.get(i);131 for (int j = i + 1; j < l.size(); j++) {132 ITestNGMethod m2 = l.get(j);133 if (!equalsEffectiveClass(m1, m2) && !dependencyExists(m1, m2, methods)) {134 Utils.log("MethodInheritance", 4, m2 + " DEPENDS ON " + m1);135 m2.addMethodDependedUpon(MethodHelper.calculateMethodCanonicalName(m1));136 }137 }138 }139 }140 }141 }142 private static boolean dependencyExists(ITestNGMethod m1, ITestNGMethod m2, ITestNGMethod[] methods) {143 return internalDependencyExists(m1, m2, methods) || internalDependencyExists(m2, m1, methods);144 }145 private static boolean internalDependencyExists(ITestNGMethod m1, ITestNGMethod m2, ITestNGMethod[] methods) {146 ITestNGMethod[] methodsNamed =147 MethodHelper.findDependedUponMethods(m1, methods);148 for (ITestNGMethod method : methodsNamed) {149 if (method.equals(m2)) {150 return true;151 }152 }153 for (String group : m1.getGroupsDependedUpon()) {154 ITestNGMethod[] methodsThatBelongToGroup =155 MethodGroupsHelper.findMethodsThatBelongToGroup(m1, methods, group);156 for (ITestNGMethod method : methodsThatBelongToGroup) {157 if (method.equals(m2)) {158 return true;159 }160 }161 }162 return false;163 }164 private static boolean equalsEffectiveClass(ITestNGMethod m1, ITestNGMethod m2) {165 try {166 Class c1 = m1.getRealClass();167 Class c2 = m2.getRealClass();168 return c1 == null ? c2 == null : c1.equals(c2);169 }170 catch(Exception ex) {171 return false;172 }173 }174 /**175 * Given a list of methods belonging to the same class hierarchy, orders them176 * from the base class to the child (if true) or from child to base class (if false)177 * @param methods178 */179 private static void sortMethodsByInheritance(List<ITestNGMethod> methods,180 boolean baseClassToChild)181 {...
Source:Listeners.java
...25 //String name = "name";26 int i=0;27 String testName = result.getMethod().getMethodName();28 try {29 //name = (String)result.getTestClass().getRealClass().getDeclaredField("usr").get(result.getInstance());30 i = (int)result.getTestClass().getRealClass().getDeclaredField("i").get(result.getInstance());31 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {32 // TODO Auto-generated catch block33 e.printStackTrace();34 }35 //testStepLogger = finalReport.createTest(result.getMethod().getMethodName()); 36 testStepLogger = finalReport.createTest(testName+"_"+ i);//creating test report in the test method name37 //assigning to the local thread38 localTest.set(testStepLogger);39 40 }41 @Override42 public void onTestSuccess(ITestResult result) {43 // TODO Auto-generated method stub44 45 WebDriver localDriver = null; // initialising so that we can get the driver from testmethod and assign to base for screenshot46 String name = "name";47 String testName = result.getMethod().getMethodName();48 //String testName1= result.getMethod().getId();49 try { //exception handling50 //assigning driver from test class to base class at that moment51 localDriver = (WebDriver)result.getTestClass().getRealClass().getDeclaredField("testDriver").get(result.getInstance());52 name = (String)result.getTestClass().getRealClass().getDeclaredField("usr").get(result.getInstance());53 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {54 // TODO Auto-generated catch block55 e.printStackTrace();56 } 57 //adding screenshot to the report58 try {//IO exception59 //localTest.get().addScreenCaptureFromPath(getScreenshot(testName.concat(testName1), localDriver));60 localTest.get().addScreenCaptureFromPath(getScreenshot(testName+" "+ name, localDriver));61 } catch (IOException e) {62 // TODO Auto-generated catch block63 e.printStackTrace();64 }65 66 localTest.get().log(Status.PASS, "User Created and validated");67 //finalReport.flush();68 }69 @Override70 public void onTestFailure(ITestResult result) {71 // TODO Auto-generated method stub72 String name = "name";73 WebDriver localDriver = null; // initialising so that we can get the driver from testmethod and assign to base for screenshot74 String testName = result.getMethod().getMethodName();75 try { //exception handling76 //assigning driver from test class to base class at that moment77 localDriver = (WebDriver)result.getTestClass().getRealClass().getDeclaredField("testDriver").get(result.getInstance());78 name = (String)result.getTestClass().getRealClass().getDeclaredField("usr").get(result.getInstance());79 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {80 // TODO Auto-generated catch block81 e.printStackTrace();82 } 83 //adding screenshot to the report84 try {//IO exception85 localTest.get().addScreenCaptureFromPath(getScreenshot(testName+" "+ name, localDriver));86 } catch (IOException e) {87 // TODO Auto-generated catch block88 e.printStackTrace();89 }90 91 localTest.get().fail(result.getThrowable());92 //finalReport.flush();...
Source:NoOpTestClass.java
...36 protected NoOpTestClass() {37 }3839 public NoOpTestClass(ITestClass testClass) {40 m_testClass= testClass.getRealClass();41 m_testName= testClass.getName();42 m_beforeSuiteMethods= testClass.getBeforeSuiteMethods();43 m_beforeTestConfMethods= testClass.getBeforeTestConfigurationMethods();44 m_beforeGroupsMethods= testClass.getBeforeGroupsMethods();45 m_beforeClassMethods= testClass.getBeforeClassMethods();46 m_beforeTestMethods= testClass.getBeforeTestMethods();47 m_afterSuiteMethods= testClass.getAfterSuiteMethods();48 m_afterTestConfMethods= testClass.getAfterTestConfigurationMethods();49 m_afterGroupsMethods= testClass.getAfterGroupsMethods();50 m_afterClassMethods= testClass.getAfterClassMethods();51 m_afterTestMethods= testClass.getAfterTestMethods();52 m_instances= testClass.getInstances(true);53 m_instanceHashes= testClass.getInstanceHashCodes();54 }5556 public void setBeforeTestMethods(ITestNGMethod[] beforeTestMethods) {57 m_beforeTestMethods= beforeTestMethods;58 }5960 public void setAfterTestMethod(ITestNGMethod[] afterTestMethods) {61 m_afterTestMethods= afterTestMethods;62 }6364 /**65 * @return Returns the afterClassMethods.66 */67 public ITestNGMethod[] getAfterClassMethods() {68 return m_afterClassMethods;69 }7071 /**72 * @return Returns the afterTestMethods.73 */74 public ITestNGMethod[] getAfterTestMethods() {75 return m_afterTestMethods;76 }7778 /**79 * @return Returns the beforeClassMethods.80 */81 public ITestNGMethod[] getBeforeClassMethods() {82 return m_beforeClassMethods;83 }8485 /**86 * @return Returns the beforeTestMethods.87 */88 public ITestNGMethod[] getBeforeTestMethods() {89 return m_beforeTestMethods;90 }9192 /**93 * @return Returns the testMethods.94 */95 public ITestNGMethod[] getTestMethods() {96 return m_testMethods;97 }9899 public ITestNGMethod[] getBeforeSuiteMethods() {100 return m_beforeSuiteMethods;101 }102103 public ITestNGMethod[] getAfterSuiteMethods() {104 return m_afterSuiteMethods;105 }106107 public ITestNGMethod[] getBeforeTestConfigurationMethods() {108 return m_beforeTestConfMethods;109 }110111 public ITestNGMethod[] getAfterTestConfigurationMethods() {112 return m_afterTestConfMethods;113 }114115 /**116 * @return all @Configuration methods that should be invoked before certain groups117 */118 public ITestNGMethod[] getBeforeGroupsMethods() {119 return m_beforeGroupsMethods;120 }121122 /**123 * @return all @Configuration methods that should be invoked after certain groups124 */125 public ITestNGMethod[] getAfterGroupsMethods() {126 return m_afterGroupsMethods;127 }128129 /**130 * @see org.testng.ITestClass#getInstanceCount()131 */132 public int getInstanceCount() {133 return m_instances.length;134 }135136 /**137 * @see org.testng.ITestClass#getInstanceHashCodes()138 */139 public long[] getInstanceHashCodes() {140 return m_instanceHashes;141 }142143 /**144 * @see org.testng.ITestClass#getInstances(boolean)145 */146 public Object[] getInstances(boolean reuse) {147 return m_instances;148 }149150 public String getName() {151 return m_testClass.getName();152 }153154 public Class getRealClass() {155 return m_testClass;156 }157158 /**159 * @see org.testng.IClass#addInstance(java.lang.Object)160 */161 public void addInstance(Object instance) {162 }163164 public void setTestClass(Class< ? > declaringClass) {165 m_testClass = declaringClass;166 }167}
Source:TestListener.java
...39 Map<String, String> params = new HashMap<String, String>();40 params = iTestResult.getTestContext().getCurrentXmlTest().getAllParameters();41 String imagePath = "Screenshots" + File.separator + params.get("platformName")42 + "_" + params.get("deviceName") + File.separator + base.getDateTime() + File.separator43 + iTestResult.getTestClass().getRealClass().getSimpleName() + File.separator + iTestResult.getName() + ".png";44 String completeImagePath = System.getProperty("user.dir") + File.separator + imagePath;45 try {46 FileUtils.copyFile(file, new File(imagePath));47 Reporter.log("This is the sample screenshot");48 Reporter.log("<a href='"+ completeImagePath + "'> <img src='"+ completeImagePath + "' height='400' width='400'/> </a>");49 ExtentReport.getTest().log(Status.PASS, "Test Passed");50 } catch (IOException e) {51 // TODO Auto-generated catch block52 e.printStackTrace();53 }54 }55 @Override56 public void onTestFailure(ITestResult iTestResult) {57 if (iTestResult.getThrowable() != null) {58 StringWriter sw = new StringWriter();59 PrintWriter pw = new PrintWriter(sw);60 iTestResult.getThrowable();61 }62 byte[] encoded = null;63 Map<String, String> params = new HashMap<String, String>();64 params = iTestResult.getTestContext().getCurrentXmlTest().getAllParameters();65 String imagePath = "Screenshots" + File.separator + params.get("platformName")66 + "_" + params.get("deviceName") + File.separator + base.getDateTime() + File.separator67 + iTestResult.getTestClass().getRealClass().getSimpleName() + File.separator + iTestResult.getName() + ".png";68 String completeImagePath = System.getProperty("user.dir") + File.separator + imagePath;69 ExtentReport.getTest().fail("Test Failed",70 MediaEntityBuilder.createScreenCaptureFromPath(completeImagePath).build());71 ExtentReport.getTest().fail("Test Failed",72 MediaEntityBuilder.createScreenCaptureFromBase64String(new String(encoded, StandardCharsets.US_ASCII)).build());73 ExtentReport.getTest().fail(iTestResult.getThrowable());74 }75 @Override76 public void onTestSkipped(ITestResult iTestResult) {77 ExtentReport.getTest().log(Status.SKIP, "Test Skipped");78 }79 @Override80 public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {81 }...
Source:ITestListenerImpl.java
...46// }47// Map<String, String> params = new HashMap<String, String>();48// params = iTestResult.getTestContext().getCurrentXmlTest().getAllParameters();49//50// String imagePath = "Screenshots" + iTestResult.getTestClass().getRealClass().getSimpleName() + File.separator + iTestResult.getName() + ".png";51//52//53//54// String completeImagePath = System.getProperty("user.dir") + File.separator + imagePath;55//56//57//58//59// try {60// FileUtils.copyFile(file, new File(imagePath));61// Reporter.log("This is the sample screenshot");62// Reporter.log("<a href='"+ completeImagePath + "'> <img src='"+ completeImagePath + "' height='400' width='400'/> </a>");63// ExtentReportListener.getTest().log(Status.PASS, "Test Passed");64// } catch (IOException e) {65// // TODO Auto-generated catch block66// e.printStackTrace();67// }68 }69 @Override70 public void onTestFailure(ITestResult iTestResult) {71// if (iTestResult.getThrowable() != null) {72// StringWriter sw = new StringWriter();73// PrintWriter pw = new PrintWriter(sw);74// iTestResult.getThrowable();75// }76// byte[] encoded = null;77// Map<String, String> params = new HashMap<String, String>();78// params = iTestResult.getTestContext().getCurrentXmlTest().getAllParameters();79//80// String imagePath = "Screenshots" + File.separator + params.get("platformName")81// + "_" + params.get("deviceName") + File.separator + base.getDateTime() + File.separator82// + iTestResult.getTestClass().getRealClass().getSimpleName() + File.separator + iTestResult.getName() + ".png";83//84//85//86// String completeImagePath = System.getProperty("user.dir") + File.separator + imagePath;87//88//89// ExtentReportListener.getTest().fail("Test Failed",90// MediaEntityBuilder.createScreenCaptureFromPath(completeImagePath).build());91// ExtentReportListener.getTest().fail("Test Failed",92// MediaEntityBuilder.createScreenCaptureFromBase64String(new String(encoded, StandardCharsets.US_ASCII)).build());93// ExtentReportListener.getTest().fail(iTestResult.getThrowable());94 }95 @Override96 public void onTestSkipped(ITestResult iTestResult) {...
Source:IClass.java
...27 String getTestName();28 /**29 * @return the Java class corresponding to this IClass.30 */31 Class getRealClass();32 Object[] getInstances(boolean create);33 int getInstanceCount();34 long[] getInstanceHashCodes();35 void addInstance(Object instance);36}...
getRealClass
Using AI Code Generation
1package com.test;2import org.testng.ITestClass;3import org.testng.annotations.Test;4public class TestClass {5public void testClass(ITestClass testClass) {6System.out.println(testClass.getRealClass().getName());7}8}
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!!