Best Testng code snippet using org.testng.Interface ITestResult.getTestContext
Source:TestReportListener.java  
...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                //...Source:ExtentTestNGReporterListener.java  
...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));...Source:IInvokedMethodYamlFactoryListenerTest.java  
...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...Source:ExtentManager.java  
...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"));...Source:MyTestListener.java  
...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}...Source:TestListener.java  
...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    }...Source:ITestListenerImpl.java  
...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());...Source:ExtentReporterNG.java  
...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()));...getTestContext
Using AI Code Generation
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();getTestContext
Using AI Code Generation
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 {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!!
