Best Testng code snippet using org.testng.Interface ITestResult.getThrowable
Source:TestNGRunner.java  
...197    @Override198    public void onTestStart(ITestResult result) {}199    @Override200    public void onTestSuccess(ITestResult result) {201      recordResult(result, ResultType.SUCCESS, result.getThrowable());202    }203    @Override204    public void onTestSkipped(ITestResult result) {205      @Nullable Throwable throwable = failedConfigurationTestClasses.get(result.getTestClass());206      if (throwable == null) {207        recordResult(result, ResultType.ASSUMPTION_VIOLATION, result.getThrowable());208      } else {209        recordResult(result, ResultType.FAILURE, throwable);210      }211    }212    @Override213    public void onTestFailure(ITestResult result) {214      recordResult(result, ResultType.FAILURE, result.getThrowable());215    }216    @Override217    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {218      recordResult(result, ResultType.FAILURE, result.getThrowable());219    }220    @Override221    public void onStart(ITestContext context) {222      // Create an intermediate stdout/stderr to capture any debugging statements (usually in the223      // form of System.out.println) the developer is using to debug the test.224      originalOut = System.out;225      originalErr = System.err;226      rawStdOutBytes = new ByteArrayOutputStream();227      rawStdErrBytes = new ByteArrayOutputStream();228      stdOutStream = streamToPrintStream(rawStdOutBytes, System.out);229      stdErrStream = streamToPrintStream(rawStdErrBytes, System.err);230      System.setOut(stdOutStream);231      System.setErr(stdErrStream);232      mustRestoreStdoutAndStderr = true;233    }234    @Override235    public void onFinish(ITestContext context) {236      if (mustRestoreStdoutAndStderr) {237        // Restore the original stdout/stderr.238        System.setOut(originalOut);239        System.setErr(originalErr);240        // Get the stdout/stderr written during the test as strings.241        stdOutStream.flush();242        stdErrStream.flush();243        mustRestoreStdoutAndStderr = false;244      }245    }246    private void recordResult(ITestResult result, ResultType type, Throwable failure) {247      String stdOut = streamToString(rawStdOutBytes);248      String stdErr = streamToString(rawStdErrBytes);249      String className = result.getTestClass().getName();250      String methodName = getTestMethodNameWithParameters(result);251      long runTimeMillis = result.getEndMillis() - result.getStartMillis();252      results.add(253          new TestResult(className, methodName, runTimeMillis, type, failure, stdOut, stdErr));254    }255    private String streamToString(ByteArrayOutputStream str) {256      try {257        return str.size() == 0 ? null : str.toString(ENCODING);258      } catch (UnsupportedEncodingException e) {259        return null;260      }261    }262    private PrintStream streamToPrintStream(ByteArrayOutputStream str, PrintStream fallback) {263      try {264        return new PrintStream(str, true /* autoFlush */, ENCODING);265      } catch (UnsupportedEncodingException e) {266        return fallback;267      }268    }269    @Override270    public void onConfigurationSuccess(ITestResult iTestResult) {}271    @Override272    public void onConfigurationFailure(ITestResult iTestResult) {273      failedConfigurationTestClasses.put(iTestResult.getTestClass(), iTestResult.getThrowable());274    }275    @Override276    public void onConfigurationSkip(ITestResult iTestResult) {}277  }278  private static class JUnitReportReporterWithMethodParameters extends JUnitReportReporter {279    @Override280    public String getTestName(ITestResult result) {281      return getTestMethodNameWithParameters(result);282    }283  }284}...Source:TestListener.java  
...94	public void onTestSkipped(ITestResult iTestResult) {95		log.debug("Entering TestListener.onTestSkipped method " + getTestMethodName(iTestResult) + " skipped!");96		// Extentreports log operation for skipped tests.97		// ExtentTestManager.getTest().log(LogStatus.SKIP, "Test Skipped");98		log.error("skip exception:: "+iTestResult.getThrowable());99		iTestResult.getThrowable().printStackTrace();100	}101	/* (non-Javadoc)102	 * @see org.testng.ITestListener#onTestFailedButWithinSuccessPercentage(org.testng.ITestResult)103	 */104	@Override105	public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {106		log.debug("Test failed but it is in defined success ratio " + getTestMethodName(iTestResult));107	}108	/* (non-Javadoc)109	 * @see org.testng.ITestListener#onStart(org.testng.ITestContext)110	 */111	@Override112	public void onStart(ITestContext context) {113		log.debug("Entering TestListener.onStart method " + context.getName());...Source:ListenerWithReports.java  
...54	    public void onTestFailure(ITestResult result) {55	        System.out.println("-------------------------");56	        System.out.println("Test " +result.getTestClass() + result.getName() + " has Failed");57	        58	        System.out.println("Error message is  " + result.getThrowable());    59	        60	        test.log(LogStatus.FAIL, result.getMethod().getMethodName()+" Test is Failed because of error " + result.getThrowable());    61	        62	        srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);63	        //FileUtils.copyFile(srcFile, new File("C:\\temp\\Demo_" +AddTime()+"_screenshot1.png"));64	        65	        try {66	            67	FileUtils.copyFile(srcFile, new File("src/POM/test_" + result.getClass().getName()68	                    + AddTime()+"_screenshot.png"));69	            70	        } catch (IOException e) {71	            // TODO Auto-generated catch block72	            e.printStackTrace();73	        }74	        75	        76	    }77	 78	    @Override79	    public void onTestSkipped(ITestResult result) {80	        System.out.println("-------------------------");81	        System.out.println("Test "+result.getTestClass()  + result.getTestName() + " was skipped");82	        System.out.println("Error message is  " + result.getThrowable());83	        test.log(LogStatus.SKIP, result.getMethod().getMethodName()+" Test is Skipped because of error" + result.getThrowable());84	    }85	 86	    @Override87	    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {88	        // TODO Auto-generated method stub89	        90	    }91	 92	    @Override93	    public void onStart(ITestContext context) {94	        System.out.println("-------------------------");95	        System.out.println("on start");96	        97	        System.setProperty("webdriver.chrome.driver", "C:\\Bhavya\\chromedriver_win32_Latest\\chromedriver.exe");...Source:ITestListenerImpl.java  
...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) {97	}98	@Override99	public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {100	}101	@Override102	public void onStart(ITestContext iTestContext) {103		//ToDo: Feature - Hard coding the feature name104		features = extentReportListener.ExtentReport().createTest(Feature.class, "LoginFeature");105	}106	@Override107	public void onFinish(ITestContext iTestContext) {...Source:CustomListeners.java  
...44			e.printStackTrace();45		}46		// ExtentReport47		// test.log(LogStatus.FAIL, result.getTestName().toUpperCase()+"Failed with48		// exception"+result.getThrowable());49		test.log(LogStatus.FAIL, "Test Failed with exception: " + result.getThrowable());50		test.log(LogStatus.FAIL, test.addScreenCapture(TestUtil.screenShotName));51		// ReportNG52		Reporter.log("Click image below to see failed test Screenshot:-");53		Reporter.log("<br>");54		Reporter.log("<br>");55		Reporter.log("<a target=\"_blank\" href=" + TestUtil.screenShotName + "><img src=" + TestUtil.screenShotName56				+ " height=200 width=200></img></a>");57		rep.endTest(test);58		rep.flush(); // without this command report wont be generated59	}60	public void onTestSkipped(ITestResult result) {61		test.log(LogStatus.SKIP, "Skipped the test:("+result.getName()+") as the runmode is set to NO, with an exceeption:("+  result.getThrowable()+")");62		rep.endTest(test);63		rep.flush(); // without this command report wont be generated64	}65	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {66	}67	public void onStart(ITestContext context) {68		69		// Using this code here wont let each parameter set to create separate test in extent report, instead it executes70		// all tests inside one test one below another.71		72		test = rep.startTest(context.getName().toUpperCase());73	}74	public void onFinish(ITestContext context) {75	}...Source:TestJiraListener.java  
...42					"joseph.ajayi@fbistech.com", "4N31bYXRZNKIk1E6It4i38FB", "BEAM");43			String issueSummary = result.getMethod().getConstructorOrMethod().getMethod().getName()44					+ " - Got failed due to some assertion or exception under Jira integration with Selenium Test Script. "45					+ "Create an automated ticket for failed test script";46			String issueDescription = result.getThrowable().getMessage() + "\n";47			issueDescription.concat(ExceptionUtils.getFullStackTrace(result.getThrowable()));48			jiraSp.createJiraTicket("Bug", issueSummary, issueDescription, "Joseph Ajayi [FBISTech - IT]");49		}50 51	}52	@Override53	public void onTestSkipped(ITestResult result) {54		// TODO Auto-generated method stub55	}56	@Override57	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {58		// TODO Auto-generated method stub59	}60	@Override61	public void onStart(ITestContext context) {...Source:ConnsTestListener.java  
...39				testResult.setAttribute("ErrorMsg ", verificationFailures.toString());40				Reporter.log(verificationFailures.toString());41				// if there is an assertion failure add it to42				// verificationFailures43				if (testResult.getThrowable() != null) {44					verificationFailures.add(testResult.getThrowable().getMessage());45				}46				StringBuffer failureMsg = new StringBuffer();47				for (int i = 0; i < size; i++) {48					failureMsg.append(verificationFailures.get(i)).append("\n");49				}50				// set merged throwable51				Throwable merged = new Throwable(failureMsg.toString());52				testResult.setThrowable(merged);53			}54		}55	}56}
...Source:LogListeners.java  
...28		LogUtil.info(result.getMethod().getMethodName() + " Passed\n");				29	}30	31	public void onTestFailure(ITestResult result) {32		LogUtil.info("Failed because of - "+ result.getThrowable());		33	}34	35	public void onTestSkipped(ITestResult result) {36		LogUtil.info("Skipped because of - "+ result.getThrowable());		37	}38	39	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {40		// TODO Auto-generated method stub		41	}4243	public void onStart(ITestContext context) {44		LogUtil.info("=========== onStart :-" + context.getName() + "===============");45	}4647	public void onFinish(ITestContext context) {48		LogUtil.info("=========== onFinish :-" + context.getName() + "===============");	49	}50}getThrowable
Using AI Code Generation
1import org.testng.ITestResult;2import org.testng.TestListenerAdapter;3public class TestNGListener extends TestListenerAdapter {4    public void onTestFailure(ITestResult tr) {5        System.out.println("Failed test case: " + tr.getName() + " and the exception is: " + tr.getThrowable().getMessage());6    }7}8import org.testng.internal.TestResult;9import org.testng.TestListenerAdapter;10public class TestNGListener extends TestListenerAdapter {11    public void onTestFailure(ITestResult tr) {12        TestResult testResult = (TestResult)tr;13        System.out.println("Failed test case: " + testResult.getName() + " and the exception is: " + testResult.getThrowable().getMessage());14    }15}16import org.testng.internal.TestResult;17import org.testng.TestListenerAdapter;18public class TestNGListener extends TestListenerAdapter {19    public void onTestFailure(ITestResult tr) {20        TestResult testResult = (TestResult)tr;21        System.out.println("Failed test case: " + testResult.getName() + " and the exception is: " + testResult.getThrowable().getMessage());22    }23}24import org.testng.internal.TestResult;25import org.testng.TestListenerAdapter;26public class TestNGListener extends TestListenerAdapter {27    public void onTestFailure(ITestResult tr) {28        TestResult testResult = (TestResult)tr;29        System.out.println("Failed test case: " + testResult.getName() + " and the exception is: " + testResult.getThrowable().getMessage());30    }31}32import org.testng.internal.TestResult;33import org.testng.TestListenerAdapter;34public class TestNGListener extends TestListenerAdapter {35    public void onTestFailure(ITestResult tr) {36        TestResult testResult = (TestResult)tr;37        System.out.println("Failed test case: " + testResult.getName() + " and the exception is: " + testResult.getThrowable().getMessage());38    }39}40import org.testng.internal.TestResult;getThrowable
Using AI Code Generation
1public void test1() {2    Assert.assertEquals(12, 13);3}4public void test2() {5    Assert.assertEquals("abc", "xyz");6}7public void test3() {8    throw new SkipException("Skipping this test");9}10public void test4() {11    throw new RuntimeException("This is a run time exception");12}13public void test5() {14    Assert.assertEquals("abc", "abc");15}16public void test6() {17    Assert.assertEquals(12, 12);18}19public void test7() {20    Assert.assertEquals("abc", "abc");21}22public void test8() {23    throw new SkipException("Skipping this test");24}25public void test9() {26    throw new RuntimeException("This is a run time exception");27}28public void test10() {29    Assert.assertEquals("abc", "abc");30}31public void test11() {32    Assert.assertEquals("abc", "abc");33}34public void test12() {35    Assert.assertEquals("abc", "abc");36}37public void test13() {38    Assert.assertEquals("abc", "abc");39}40public void test14() {41    throw new SkipException("Skipping this test");42}43public void test15() {44    throw new RuntimeException("This is a run time exception");45}46public void test16() {47    Assert.assertEquals("abc", "abc");48}49public void test17() {50    Assert.assertEquals("abc", "abc");51}52public void test18() {53    Assert.assertEquals("abc", "abc");54}55public void test19() {56    Assert.assertEquals("abc", "abc");57}58public void test20() {59    throw new SkipException("Skipping this test");60}61public void test21() {62    throw new RuntimeException("This is a run time exception");63}64public void test22() {65    Assert.assertEquals("abc", "abc");66}67public void test23() {68    Assert.assertEquals("abc", "abc");69}70public void test24() {71    Assert.assertEquals("abc", "abc");72}73public void test25() {74    Assert.assertEquals("abc", "abc");75}76public void test26() {77    throw new SkipException("Skipping this test");78}79public void test27() {80    throw new RuntimeException("getThrowable
Using AI Code Generation
1import org.testng.ITestResult;2public class TestResult {3public static void main(String[] args) {4ITestResult result = null;5Throwable throwable = result.getThrowable();6}7}8import org.testng.ITestResult;9public class TestResult {10public static void main(String[] args) {11ITestResult result = null;12Throwable throwable = result.getThrowable();13}14}15import org.testng.ITestResult;16public class TestResult {17public static void main(String[] args) {18ITestResult result = null;19Throwable throwable = result.getThrowable();20}21}22import org.testng.ITestResult;23public class TestResult {24public static void main(String[] args) {25ITestResult result = null;26Throwable throwable = result.getThrowable();27}28}29import org.testng.ITestResult;30public class TestResult {31public static void main(String[] args) {32ITestResult result = null;33Throwable throwable = result.getThrowable();34}35}36import org.testng.ITestResult;37public class TestResult {38public static void main(String[] args) {39ITestResult result = null;40Throwable throwable = result.getThrowable();41}42}43import org.testng.ITestResult;44public class TestResult {45public static void main(String[] args) {46ITestResult result = null;47Throwable throwable = result.getThrowable();48}49}50import org.testng.ITestResult;51public class TestResult {52public static void main(String[] args) {53ITestResult result = null;54Throwable throwable = result.getThrowable();55}56}57import org.testng.ITestResult;58public class TestResult {59public static void main(String[] args) {60ITestResult result = null;61Throwable throwable = result.getThrowable();62}63}64import org.testng.ITestResult;65public class TestResult {66public static void main(String[] args) {67ITestResult result = null;getThrowable
Using AI Code Generation
1import org.testng.ITestResult;2public class TestResult {3public static void main(String[] args) {4	ITestResult result = null;5	System.out.println(result.getThrowable());6}7}8	at TestResult.main(TestResult.java:10)getThrowable
Using AI Code Generation
1package com.test;2import org.testng.ITestResult;3import org.testng.Reporter;4import org.testng.annotations.AfterMethod;5import org.testng.annotations.Test;6public class TestNGTest {7public void testMethod1() {8Reporter.log("TestNGTest.testMethod1()");9throw new RuntimeException("This is a test exception");10}11public void testMethod2() {12Reporter.log("TestNGTest.testMethod2()");13}14public void afterMethod(ITestResult result) {15if(result.getStatus() == ITestResult.FAILURE) {16Reporter.log("Exception message: " + result.getThrowable().getMessage());17}18}19}20TestNGTest.testMethod1()21TestNGTest.testMethod2()22<line message="TestNGTest.testMethod1()" />23at com.test.TestNGTest.testMethod1(TestNGTest.java:13)24at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)25at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)26at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)27at java.lang.reflect.Method.invoke(Method.java:498)28at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)29at org.testng.internal.Invoker.invokeMethod(Invoker.java:599)getThrowable
Using AI Code Generation
1package com.automation;2import org.testng.ITestResult;3import org.testng.annotations.AfterMethod;4import org.testng.annotations.Test;5public class TestNG_Stacktrace {6    public void testMethod1() {7        System.out.println("TestNG_Stacktrace.testMethod1");8        int i = 1 / 0;9    }10    public void testMethod2() {11        System.out.println("TestNG_Stacktrace.testMethod2");12        int i = 1 / 0;13    }14    public void afterMethod(ITestResult result) {15        if (result.getStatus() == ITestResult.FAILURE) {16            System.out.println("Failed!");17            System.out.println("Exception is: " + result.getThrowable());18        }19    }20}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!!
