How to use getTestContext method of org.testng.Interface ITestResult class

Best Testng code snippet using org.testng.Interface ITestResult.getTestContext

Source:TestReportListener.java Github

copy

Full Screen

...71 }72 //循环suite73 for (ISuiteResult r : result.values()) {74 ExtentTest resultNode;75 ITestContext context = r.getTestContext();76 //获取类名与接口中文名的对应77 ITestNGMethod[] methods=context.getAllTestMethods();78 onetest += suite.getName()+"-"+context.getName() +"-------------------------------------------<br>";79 //类里面的方法个数80 if(methods != null && methods.length >0) {81 for (int i=0;i<methods.length;i++){82 if(onetest.contains(methods[i].getTestClass().getName()) ==false ) {83 onetest += methods[i].getTestClass().getName() + "-->" + methods[i].getInstance().toString() + "<br>";84 }85 }86 }87 //如过在这个之前则赋值给它88 if(context.getStartDate().before(mindate) == true){89 mindate=context.getStartDate();90 }91 if(createSuiteResultNode){92 //没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。93 if( null == suiteTest){94 resultNode = extent.createTest(r.getTestContext().getName());95 }else{96 resultNode = suiteTest.createNode(r.getTestContext().getName());97 }98 }else{99 resultNode = suiteTest;100 }101 if(resultNode != null){102 //写标题103 resultNode.getModel().setName(suite.getName()+"---"+r.getTestContext().getName());104 //分配种类105 if(resultNode.getModel().hasCategory()){106 resultNode.assignCategory(r.getTestContext().getName());107 }else{108 resultNode.assignCategory(suite.getName(),r.getTestContext().getName());109 }110 //放置时间111 resultNode.getModel().setStartTime(r.getTestContext().getStartDate());112 resultNode.getModel().setEndTime(r.getTestContext().getEndDate());113 //统计SuiteResult下的数据114 int passSize = r.getTestContext().getPassedTests().size();115 int failSize = r.getTestContext().getFailedTests().size();116 int skipSize = r.getTestContext().getSkippedTests().size();117 //System.out.println(suite.getName()+"---"+r.getTestContext().getName() +"成功个数"+ passSize);118 reportcontext = reportcontext +"\n";119 double prate=(double)passSize/(double)(passSize+failSize+skipSize)*100.00;120 suitePassSize += passSize;121 suiteFailSize += failSize;122 suiteSkipSize += skipSize;123 //只要有一个fail ,整个状态为fail124 if(failSize>0){125 resultNode.getModel().setStatus(Status.FAIL);126 }127 //添加描述128 resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));129 }130// ExtentTest tn=resultNode.createNode("测试烊");131 //...

Full Screen

Full Screen

Source:ExtentTestNGReporterListener.java Github

copy

Full Screen

...45 createSuiteResultNode=true;46 }47 for (ISuiteResult r : result.values()) {48 ExtentTest resultNode;49 ITestContext context = r.getTestContext();50 if(createSuiteResultNode){51 //没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。52 if( null == suiteTest){53 resultNode = extent.createTest(r.getTestContext().getName());54 }else{55 resultNode = suiteTest.createNode(r.getTestContext().getName());56 }57 }else{58 resultNode = suiteTest;59 }60 if(resultNode != null){61 resultNode.getModel().setName(suite.getName()+" : "+r.getTestContext().getName());62 if(resultNode.getModel().hasCategory()){63 resultNode.assignCategory(r.getTestContext().getName());64 }else{65 resultNode.assignCategory(suite.getName(),r.getTestContext().getName());66 }67 resultNode.getModel().setStartTime(r.getTestContext().getStartDate());68 resultNode.getModel().setEndTime(r.getTestContext().getEndDate());69 //统计SuiteResult下的数据70 int passSize = r.getTestContext().getPassedTests().size();71 int failSize = r.getTestContext().getFailedTests().size();72 int skipSize = r.getTestContext().getSkippedTests().size();73 suitePassSize += passSize;74 suiteFailSize += failSize;75 suiteSkipSize += skipSize;76 if(failSize>0){77 resultNode.getModel().setStatus(Status.FAIL);78 }79 resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));80 }81 buildTestNodes(resultNode,context.getFailedTests(), Status.FAIL);82 buildTestNodes(resultNode,context.getSkippedTests(), Status.SKIP);83 buildTestNodes(resultNode,context.getPassedTests(), Status.PASS);84 }85 if(suiteTest!= null){86 suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",suitePassSize,suiteFailSize,suiteSkipSize));...

Full Screen

Full Screen

Source:IInvokedMethodYamlFactoryListenerTest.java Github

copy

Full Screen

...89 @Test @JdutResource90 void loadAndClean() throws SQLException91 {92 Object[] callbackArgs = TestMethodInfoKeeper.getCallbackArgs(getClass(), "loadAndClean");93 ITestContext testContext = ((ITestResult)callbackArgs[1]).getTestContext();94 YamlFactoryListenerBase.setDataSource(testContext, getDataSource());95 invokeCallback(testedListener::beforeInvocation, callbackArgs);96 /**97 * Asserts the building of data98 */99 String checkData = "SELECT COUNT(*) FROM tab_22 WHERE t22_id = 33";100 assertData(checkData, 2);101 // :~)102 invokeCallback(testedListener::afterInvocation, callbackArgs);103 YamlFactoryListenerBase.removeDataSource(testContext);104 /**105 * Asserts the clean of data106 */107 assertData(checkData, 0);108 // :~)109 }110 /**111 * Tests the build/clean on method without @JdutResource(nothing happened).112 */113 @Test114 void withoutAnnotation() throws SQLException115 {116 Object[] callbackArgs = TestMethodInfoKeeper.getCallbackArgs(getClass(), "withoutAnnotation");117 ITestContext testContext = ((ITestResult)callbackArgs[1]).getTestContext();118 YamlFactoryListenerBase.setDataSource(testContext, getDataSource());119 invokeCallback(testedListener::beforeInvocation, callbackArgs);120 /**121 * Asserts the building of data122 */123 String checkData = "SELECT COUNT(*) FROM tab_22 WHERE t22_id = 33";124 assertData(checkData, 0);125 // :~)126 invokeCallback(testedListener::afterInvocation, callbackArgs);127 YamlFactoryListenerBase.removeDataSource(testContext);128 /**129 * Asserts the clean of data130 */131 assertData(checkData, 0);132 // :~)133 }134 /**135 * Tests one time only(as true) for multi-time calling of a testing method by @DataProvider.136 */137 @Test(dataProvider="multiTimes")138 @JdutResource @TestNGConfig(oneTimeOnly=true)139 void loadAndCleanForOneTimeOnly(int v) throws SQLException140 {141 Object[] callbackArgs = TestMethodInfoKeeper.getCallbackArgs(getClass(), "loadAndCleanForOneTimeOnly");142 ITestContext testContext = ((ITestResult)callbackArgs[1]).getTestContext();143 YamlFactoryListenerBase.setDataSource(testContext, getDataSource());144 invokeCallback(testedListener::beforeInvocation, callbackArgs);145 /**146 * Asserts the building of data147 */148 String checkData = "SELECT COUNT(*) FROM tab_45 WHERE t45_id = 77";149 if (v == FIRST_TIME) {150 assertData(checkData, 1);151 }152 // :~)153 invokeCallback(testedListener::afterInvocation, callbackArgs);154 YamlFactoryListenerBase.removeDataSource(testContext);155 /**156 * Asserts the clean of data157 */158 if (v == LAST_TIME) {159 assertData(checkData, 2);160 }161 // :~)162 }163 /**164 * Tests one time only(as false) for multi-time calling of a testing method by @DataProvider.165 */166 @Test(dataProvider="multiTimes")167 @JdutResource @TestNGConfig(oneTimeOnly=false)168 void loadAndCleanForMultipleTimes(int v) throws SQLException169 {170 Object[] callbackArgs = TestMethodInfoKeeper.getCallbackArgs(getClass(), "loadAndCleanForMultipleTimes");171 ITestContext testContext = ((ITestResult)callbackArgs[1]).getTestContext();172 YamlFactoryListenerBase.setDataSource(testContext, getDataSource());173 invokeCallback(testedListener::beforeInvocation, callbackArgs);174 /**175 * Asserts the building of data176 */177 String checkData = "SELECT COUNT(*) FROM tab_63 WHERE t63_id = 89";178 if (v == FIRST_TIME) {179 assertData(checkData, 1);180 }181 // :~)182 invokeCallback(testedListener::afterInvocation, callbackArgs);183 YamlFactoryListenerBase.removeDataSource(testContext);184 /**185 * Asserts the clean of data...

Full Screen

Full Screen

Source:ExtentManager.java Github

copy

Full Screen

...47 * @param iTestResult48 */49 public static void setTestParams(ITestResult iTestResult, String kindOfTeste) {50 Object parameterMap = new HashMap();51 if (iTestResult.getTestContext().getCurrentXmlTest().getAllParameters().size() > 0) {52 parameterMap = iTestResult.getTestContext().getCurrentXmlTest().getAllParameters();53 //System.out.println("Parameters for Test: " +iTestResult.getMethod().getMethodName()+"\nParameters for Test: "+parameterMap+"");54 } else {55 parameterMap = "No parameters Found";56 }57 switch (kindOfTeste) {58 case "API":59 ExtentApiTestListeners.getInstance().debug(HTML_TAG_BR + "Suite: " + iTestResult.getTestContext().getSuite().getName() + HTML_TAG_PRE60 + HTML_TAG_BR + "Test: " + iTestResult.getTestContext().getName()61 + HTML_TAG_BR + "Method: " + iTestResult.getMethod().getMethodName()62 + HTML_TAG_BR + "Params: " + parameterMap + HTML_TAG_PRE_CLOSE);63 break;64 default:65 ExtentTestListeners.getInstance().debug(HTML_TAG_BR + "Suite: " + iTestResult.getTestContext().getSuite().getName() + HTML_TAG_PRE66 + HTML_TAG_BR + "Test: " + iTestResult.getTestContext().getName()67 + HTML_TAG_BR + "Method: " + iTestResult.getMethod().getMethodName()68 + HTML_TAG_BR + "Params: " + HTML_TAG_BR + parameterMap + HTML_TAG_PRE_CLOSE);69 break;70 }71 }72 /**73 * Set Environment variables at report74 */75 public static void setReportParams() {76 //Environment77 ExtentTestListeners.getRunningReport().setSystemInfo("User Name", System.getProperty("user.name"));78 ExtentTestListeners.getRunningReport().setSystemInfo("Time Zone", System.getProperty("user.timezone"));79 ExtentTestListeners.getRunningReport().setSystemInfo("OS Name", System.getProperty("os.name"));80 ExtentTestListeners.getRunningReport().setSystemInfo("User language", System.getProperty("user.language"));...

Full Screen

Full Screen

Source:MyTestListener.java Github

copy

Full Screen

...92 */93 @Override94 public void onTestStart(ITestResult arg0) {95 // TODO Auto-generated method stub96 String suiteName =arg0.getTestContext().getSuite().getName();97 String caseName=arg0.getTestContext().getName();98 data.setCurrentTestCase(caseName);99 ReportCase reportCase = new ReportCase();100 report.getCurrentReportSuite().addReportCase(reportCase);101 report.setCurrentReportCase(reportCase);102 String seniorProtocol = (String) arg0.getTestContext().getAttribute("seniorProtocol");103 if (!seniorProtocol.equalsIgnoreCase("webdriver")) {104 Object[] o = arg0.getParameters();105 Map<String, String> caseMap = (Map) o[0];106 //如果是接口测试的情况下读取EXCEL 里面的用例名称107 String interfaceCaseName = caseMap.get("用例名称");108 reportCase.setCaseName(interfaceCaseName);109 reportCase.setCaseType("interface");110 arg0.getTestContext().getCurrentXmlTest().setName(interfaceCaseName);111 arg0.getTestContext().setAttribute("caseName", interfaceCaseName);112 logger.info("开始执行测试用例:" + interfaceCaseName + "--测试方法:" + arg0.getName());113 } else {114 reportCase.setCaseType("webDriver");115 reportCase.setCaseName(caseName);116 logger.info("开始执行测试用例:" + caseName + "--测试方法:" + arg0.getName());117 }118 }119 /**120 * 每次测试成功时执行121 *122 * @param arg0123 */124 @Override125 public void onTestSuccess(ITestResult arg0) {126 // TODO Auto-generated method stub127// MyTestResult myTestResult=(MyTestResult)arg0;128// myTestResult.setName((String)arg0.getTestContext().getAttribute("caseName"));129 }130}...

Full Screen

Full Screen

Source:TestListener.java Github

copy

Full Screen

...36 // TODO Auto-generated catch block37 e1.printStackTrace();38 }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 }...

Full Screen

Full Screen

Source:ITestListenerImpl.java Github

copy

Full Screen

...44// e1.printStackTrace();45//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());...

Full Screen

Full Screen

Source:ExtentReporterNG.java Github

copy

Full Screen

...22 + "Extent.html", true);23 for (ISuite suite : suites) {24 Map<String, ISuiteResult> result = suite.getResults();25 for (ISuiteResult r : result.values()) {26 ITestContext context = r.getTestContext();27 buildTestNodes(context.getPassedTests(), LogStatus.PASS);28 buildTestNodes(context.getFailedTests(), LogStatus.FAIL);29 buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);30 }31 }32 extent.flush();33 extent.close();34 }35 private void buildTestNodes(IResultMap tests, LogStatus status) {36 ExtentTest test;37 if (tests.size() > 0) {38 for (ITestResult result : tests.getAllResults()) {39 test = extent.startTest(result.getMethod().getMethodName());40 test.setStartedTime(getTime(result.getStartMillis()));...

Full Screen

Full Screen

getTestContext

Using AI Code Generation

copy

Full Screen

1String testMethodName = getTestContext().getCurrentXmlTest().getName();2String testMethodName = getTestContext().getCurrentXmlTest().getName();3String testMethodName = getTestContext().getCurrentXmlTest().getName();4String testMethodName = getTestContext().getCurrentXmlTest().getName();5String testMethodName = getTestContext().getCurrentXmlTest().getName();6String testMethodName = getTestContext().getCurrentXmlTest().getName();7String testMethodName = getTestContext().getCurrentXmlTest().getName();8String testMethodName = getTestContext().getCurrentXmlTest().getName();9String testMethodName = getTestContext().getCurrentXmlTest().getName();10String testMethodName = getTestContext().getCurrentXmlTest().getName();11String testMethodName = getTestContext().getCurrentXmlTest().getName();12String testMethodName = getTestContext().getCurrentXmlTest().getName();13String testMethodName = getTestContext().getCurrentXmlTest().getName();

Full Screen

Full Screen

getTestContext

Using AI Code Generation

copy

Full Screen

1public class TestNGTestContext {2 public void testContext(ITestContext context) {3 System.out.println("Test context is: " + context);4 }5}6public class TestNGTestContextListener implements ITestListener {7 public void onTestStart(ITestResult result) {8 System.out.println("Test context is: " + result.getTestContext());9 }10}11public class TestNGTestContextListener implements IInvokedMethodListener {12 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {13 System.out.println("Test context is: " + testResult.getTestContext());14 }15}16public class TestNGTestContextListener implements IHookable {17 public void run(IHookCallBack callBack, ITestResult testResult) {18 System.out.println("Test context is: " + testResult.getTestContext());19 }20}21public class TestNGTestContextListener implements ITestListener {

Full Screen

Full Screen

TestNG tutorial

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.

Chapters

  1. JUnit 5 vs. TestNG: Compare and explore the core differences between JUnit 5 and TestNG from the Selenium WebDriver viewpoint.
  2. Installing TestNG in Eclipse: Start installing the TestNG Plugin and learn how to set up TestNG in Eclipse to begin constructing a framework for your test project.
  3. Create TestNG Project in Eclipse: Get started with creating a TestNG project and write your first TestNG test script.
  4. Automation using TestNG: Dive into how to install TestNG in this Selenium TestNG tutorial, the fundamentals of developing an automation script for Selenium automation testing.
  5. Parallel Test Execution in TestNG: Here are some essential elements of parallel testing with TestNG in this Selenium TestNG tutorial.
  6. Creating TestNG XML File: Here is a step-by-step tutorial on creating a TestNG XML file to learn why and how it is created and discover how to run the TestNG XML file being executed in parallel.
  7. Automation with Selenium, Cucumber & TestNG: Explore for an in-depth tutorial on automation using Selenium, Cucumber, and TestNG, as TestNG offers simpler settings and more features.
  8. JUnit Selenium Tests using TestNG: Start running your regular and parallel tests by looking at how to run test cases in Selenium using JUnit and TestNG without having to rewrite the tests.
  9. Group Test Cases in TestNG: Along with the explanation and demonstration using relevant TestNG group examples, learn how to group test cases in TestNG.
  10. Prioritizing Tests in TestNG: Get started with how to prioritize test cases in TestNG for Selenium automation testing.
  11. Assertions in TestNG: Examine what TestNG assertions are, the various types of TestNG assertions, and situations that relate to Selenium automated testing.
  12. DataProviders in TestNG: Deep dive into learning more about TestNG's DataProvider and how to effectively use it in our test scripts for Selenium test automation.
  13. Parameterization in TestNG: Here are the several parameterization strategies used in TestNG tests and how to apply them in Selenium automation scripts.
  14. TestNG Listeners in Selenium WebDriver: Understand the various TestNG listeners to utilize them effectively for your next plan when working with TestNG and Selenium automation.
  15. TestNG Annotations: Learn more about the execution order and annotation attributes, and refer to the prerequisites required to set up TestNG.
  16. TestNG Reporter Log in Selenium: Find out how to use the TestNG Reporter Log and learn how to eliminate the need for external software with TestNG Reporter Class to boost productivity.
  17. TestNG Reports in Jenkins: Discover how to generate TestNG reports in Jenkins if you want to know how to create, install, and share TestNG reports in Jenkins.

Certification

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.

YouTube

Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful