Best Testng code snippet using org.testng.Interface IResultMap.size
Source:MyReporterListener.java
...140 startResultSummaryTable("methodOverview");141 int testIndex = 1;142 for (ISuite suite : suites) 143 {144 if (suites.size() > 1) 145 {146 titleRow(suite.getName(), 5);147 }148 Map<String, ISuiteResult> r = suite.getResults();149 for (ISuiteResult r2 : r.values())150 {151 ITestContext testContext = r2.getTestContext();152 String testName = testContext.getName();153 m_testIndex = testIndex;154 resultSummary(suite, testContext.getFailedConfigurations(),155 testName, "failed", " (configuration methods)");156 resultSummary(suite, testContext.getFailedTests(), testName,157 "failed", "");158 resultSummary(suite, testContext.getSkippedConfigurations(),159 testName, "skipped", " (configuration methods)");160 resultSummary(suite, testContext.getSkippedTests(), testName,161 "skipped", "");162 resultSummary(suite, testContext.getPassedTests(), testName,163 "passed", "");164 testIndex++;165 }166 }167 m_out.println("</table>");168 }169 170/** Creates a section showing known results for each method */171 172 protected void generateMethodDetailReport(List<ISuite> suites) 173 {174 m_methodIndex = 0;175 for (ISuite suite : suites) {176 Map<String, ISuiteResult> r = suite.getResults();177 for (ISuiteResult r2 : r.values()) {178 ITestContext testContext = r2.getTestContext();179 if (r.values().size() > 0) 180 {181 m_out.println("<h1><div id='"+testContext.getName()+"'>" + testContext.getName() + "</h1></div>");182 }183 resultDetail(testContext.getFailedConfigurations());184 resultDetail(testContext.getFailedTests());185 resultDetail(testContext.getSkippedConfigurations());186 resultDetail(testContext.getSkippedTests());187 resultDetail(testContext.getPassedTests());188 }189 }190 }191 192 /**193 * @param tests194 */195 private void resultSummary(ISuite suite, IResultMap tests, String testname,196 String style, String details) {197 if (tests.getAllResults().size() > 0) {198 StringBuffer buff = new StringBuffer();199 String lastClassName = "";200 int mq = 0;201 int cq = 0;202 for (ITestNGMethod method : getMethodSet(tests, suite)) {203 m_row += 1;204 m_methodIndex += 1;205 ITestClass testClass = method.getTestClass();206 String className = testClass.getName();207 if (mq == 0) {208 String id = (m_testIndex == null ? null : "t"209 + Integer.toString(m_testIndex));210 titleRow(testname + " — " + style + details, 5, id);211 m_testIndex = null;212 }213 if (!className.equalsIgnoreCase(lastClassName)) {214 if (mq > 0) {215 cq += 1;216 m_out.print("<tr class=\"" + style217 + (cq % 2 == 0 ? "even" : "odd") + "\">"218 + "<td");219 if (mq > 1) {220 m_out.print(" rowspan=\"" + mq + "\"");221 }222 m_out.println(">" + lastClassName + "</td>" + buff);223 }224 mq = 0;225 buff.setLength(0);226 lastClassName = className;227 }228 Set<ITestResult> resultSet = tests.getResults(method);229 long end = Long.MIN_VALUE;230 long start = Long.MAX_VALUE;231 for (ITestResult testResult : tests.getResults(method))232 {233 if (testResult.getEndMillis() > end) 234 {235 end = testResult.getEndMillis();236 }237 if (testResult.getStartMillis() < start) 238 {239 start = testResult.getStartMillis();240 }241 }242 mq += 1;243 if (mq > 1) 244 {245 buff.append("<tr class=\"" + style246 + (cq % 2 == 0 ? "odd" : "even") + "\">");247 }248 String description = method.getDescription();249 String testInstanceName = resultSet250 .toArray(new ITestResult[] {})[0].getTestName();251 buff.append("<td><a href=\"#m"252 + m_methodIndex253 + "\">"254 + qualifiedName(method)255 + " "256 + (description != null && description.length() > 0 ? "(\""257 + description + "\")"258 : "")259 + "</a>"260 + (null == testInstanceName ? "" : "<br>("261 + testInstanceName + ")") + "</td>"262 + "<td class=\"numi\">" + resultSet.size() + "</td>"263 + "<td>" + start + "</td>" + "<td class=\"numi\">"264 + (end - start) + "</td>" + "</tr>");265 }266 if (mq > 0) {267 cq += 1;268 m_out.print("<tr class=\"" + style269 + (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td");270 if (mq > 1) {271 m_out.print(" rowspan=\"" + mq + "\"");272 }273 m_out.println(">" + lastClassName + "</td>" + buff);274 }275 }276 }277 278 /** Starts and defines columns result summary table */279 280 private void startResultSummaryTable(String style) 281 {282 tableStart(style, "summary");283 m_out.println("<tr><th>Class</th>"284 + "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");285 m_row = 0;286 }287 private String qualifiedName(ITestNGMethod method) 288 {289 StringBuilder addon = new StringBuilder();290 String[] groups = method.getGroups();291 int length = groups.length;292 if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {293 addon.append("(");294 for (int i = 0; i < length; i++) {295 if (i > 0) {296 addon.append(", ");297 }298 addon.append(groups[i]);299 }300 addon.append(")");301 }302 return "<b>" + method.getMethodName() + "</b> " + addon;303 }304 305 private void resultDetail(IResultMap tests) {306 for (ITestResult result : tests.getAllResults()) {307 ITestNGMethod method = result.getMethod();308 m_methodIndex++;309 //String cname = method.getTestClass().getName();310 //m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"311 // + method.getMethodName() + "</h2>");312 Set<ITestResult> resultSet = tests.getResults(method);313 generateForResult(result, method, resultSet.size());314 m_out.println("<hr>");315 m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");316 }317 }318 319 private void generateForResult(ITestResult ans, ITestNGMethod method,320 int resultSetSize) {321 Object[] parameters = ans.getParameters();322 boolean hasParameters = parameters != null && parameters.length > 0;323 if (hasParameters) {324 tableStart("result", null);325 m_out.print("<tr class=\"param\">");326 for (int x = 1; x <= parameters.length; x++) {327 m_out.print("<th>Param." + x + "</th>");328 }329 m_out.println("</tr>");330 m_out.print("<tr class=\"param stripe\">");331 for (Object p : parameters) {332 m_out.println("<td>" + Utils.escapeHtml(Utils.toString(p))333 + "</td>");334 }335 m_out.println("</tr>");336 }337 List<String> msgs = Reporter.getOutput(ans);338 boolean hasReporterOutput = msgs.size() > 0;339 340 341 Throwable exception = ans.getThrowable();342 boolean hasThrowable = exception != null;343 if (hasReporterOutput || hasThrowable) {344 if (hasParameters) {345 m_out.print("<tr><td");346 if (parameters.length > 1) {347 m_out.print(" colspan=\"" + parameters.length + "\"");348 }349 m_out.println(">");350 } else {351 m_out.println("<div>");352 }353 if (hasReporterOutput) {354 if (hasThrowable) {355 //m_out.println("<h3>Test Messages</h3>");356 }357 for (String line : msgs) {358 m_out.println(line + "<br/>");359 }360 }361 if (hasThrowable) {362 boolean wantsMinimalOutput = ans.getStatus() == ITestResult.SUCCESS;363 if (hasReporterOutput) {364 m_out.println("<h3>"365 + (wantsMinimalOutput ? "Expected Exception"366 : "Failure") + "</h3>");367 }368 generateExceptionReport(exception, method);369 }370 if (hasParameters) {371 m_out.println("</td></tr>");372 } else {373 m_out.println("</div>");374 }375 }376 if (hasParameters) {377 m_out.println("</table>");378 }379 }380 381 protected void generateExceptionReport(Throwable exception,382 ITestNGMethod method) {383 m_out.print("<div class=\"stacktrace\">");384 385 String str=Utils.stackTrace(exception, true)[0];386 scanner = new Scanner(str);387 String firstLine = scanner.nextLine();388 m_out.println(firstLine);389 m_out.println("</div>");390 }391 /**392 * Since the methods will be sorted chronologically, we want to return the393 * ITestNGMethod from the invoked methods.394 */395 396 private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) {397 List<IInvokedMethod> r = Lists.newArrayList();398 List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();399 for (IInvokedMethod im : invokedMethods) {400 if (tests.getAllMethods().contains(im.getTestMethod())) {401 r.add(im);402 }403 }404 Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());405 List<ITestNGMethod> result = Lists.newArrayList();406 // Add all the invoked methods407 for (IInvokedMethod m : r) {408 result.add(m.getTestMethod());409 }410 // Add all the methods that weren't invoked (e.g. skipped) that we411 // haven't added yet412 for (ITestNGMethod m : tests.getAllMethods()) {413 if (!result.contains(m)) {414 result.add(m);415 }416 }417 return result;418 }419 420 @SuppressWarnings("unused")421 public void generateSuiteSummaryReport(List<ISuite> suites) {422 tableStart("testOverview", "summary");423 m_out.print("<tr>"); 424 tableColumnStart("Test CaseID");425 tableColumnStart("Test Scenarios");426 tableColumnStart("Result");427 tableColumnStart("Start Time-<br/>End Time");428 tableColumnStart("Total<br/>Time");429 tableColumnStart("");430 m_out.println("</tr>");431 NumberFormat formatter = new DecimalFormat("#,##0.0");432 SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yy hh:mm:ss a");433 int qty_tests = 0;434 int qty_pass_m = 0;435 int qty_pass_s = 0;436 int qty_skip = 0;437 int qty_fail = 0;438 int total_pass_s=0;439 int total_fail=0;440 int total_skip=0;441 long time_start = Long.MAX_VALUE;442 long time_end = Long.MIN_VALUE;443 m_testIndex = 1;444 for (ISuite suite : suites)445 {446 if (suites.size() >= 1) 447 {448 titleRow(suite.getName(), 7);449 }450 Map<String, ISuiteResult> tests = suite.getResults();451 for (ISuiteResult r : tests.values()) 452 {453 qty_tests += 1;454 455 456 //Getting Method Name457 ITestContext overview = r.getTestContext();458 459 MethodDetails MD= (MethodDetails) details.get(overview.getName());460 System.out.println("md : "+overview.getName());461 startSummaryRow(MD.getTestCaseID()); 462 printTestCaseName(overview.getName());463 464 //get Passed Methods Number465 int q = getMethodSet(overview.getPassedTests(), suite).size();466 /* qty_pass_m += q;467 summaryCell(q, Integer.MAX_VALUE);*/468 //Get passed Tests Number469 q = overview.getPassedTests().size();470 qty_pass_s += q;471 // summaryCell(q, Integer.MAX_VALUE);472 //Get Skipped Tests Number 473 q = getMethodSet(overview.getSkippedTests(), suite).size();474 qty_skip += q;475 // summaryCell(q, 0);476 //Get Failed Tests Number477 q = getMethodSet(overview.getFailedTests(), suite).size();478 qty_fail += q;479 //summaryCell(q, 0);480 if(qty_pass_s>0)481 {482 summaryCell("<center><label style='color:green;'>Passed</label></center>");483 total_pass_s+=qty_pass_s;484 qty_pass_s=0;485 486 }487 else if(qty_fail>0)488 {489 summaryCell("<center><label style='color:red;'>Failed</label></center>");490 total_fail+=qty_fail;491 qty_fail=0;492 }493 else if(qty_skip>0)494 {495 summaryCell("<center><label style='color:yellow;'>Skipped</label></center>");496 total_skip+=qty_skip;497 qty_skip=0;498 }499 500 // NEW ----DateFunctions.dateToDayAndTime(overview.getStartDate())501 502 summaryCell(503 df.format(overview.getStartDate()).toString()+" -- "+df.format(overview.getEndDate()).toString(),504 true);505 m_out.println("</td>");506 507 m_out.println("</td>");508 time_start = Math.min(overview.getStartDate().getTime(),509 time_start);510 time_end = Math.max(overview.getEndDate().getTime(), time_end);511 summaryCelltotal(512 formatter.format((overview.getEndDate().getTime() - overview513 .getStartDate().getTime()) / 1000.)514 + " seconds", true);515 516 m_out.println("</tr>");517 m_testIndex++;518 }519 }520 if (qty_tests >=1) {521 m_out.println("<tr class=\"total\"><td>Total</td>");522 m_out.println("<td>Passed:"+total_pass_s+"<br/>Failed:"+total_fail+"<br/>Skipped:"+total_skip+"</td>");523 summaryCell(" ", true);524 summaryCell(" ", true);525 summaryCell(" ", true);526 pass=total_pass_s;527 fail=total_fail;528 skip=total_skip;529 System.out.println("pass test cases:-"+pass);530 System.out.println("fail test cases:-"+fail);531 summaryCellEnd(formatter.format(((time_end - time_start) / 1000.) / 60.)+ " minutes", true);532 }533 m_out.println("</table>");534 }535 private void summaryCell(String val) {536 /* StringBuffer b = new StringBuffer();537 for (String v : val) {538 b.append(v + " ");539 }*/540 summaryCelltotal(val, true);541 }542 private void summaryCell(String v, boolean isgood) {543 m_out.print("<td class=\"numi" + (isgood ? "" : "_attn") + "\">" + v544 + "</td>");545 }546 private void summaryCelltotal(String v, boolean isgood) {547 m_out.print("<td class=\"numi2" + (isgood ? "" : "_attn") + "\">" + v548 + "</td>");549 }550 private void summaryCellEnd(String v, boolean isgood) {551 m_out.print("<td colspan=2 class=\"numi" + (isgood ? "" : "_attn") + "\"><center>" + v552 + "</center></td>");553 }554 private void startSummaryRow(String label) {555 m_row += 1;556 m_out.print("<tr"557 + (m_row % 2 == 0 ? " class=\"stripe\"" : "")558 + "><td width='5%'>" + label + "</td>");559 }560 private void printTestCaseName(String label) {561 m_row += 1;562 m_out.print("<td style=\"text-align:left;padding-right:2em;width:20%\"><a href='#"+label+"'>" + label + "</a>" + "</td>");563 }564 565 /* private void summaryCell(int v, int maxexpected) {566 summaryCell(String.valueOf(v), v <= maxexpected);567 }*/568 private void tableStart(String cssclass, String id) {569 m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""570 + (cssclass != null ? " class=\"" + cssclass + "\""571 : " style=\"padding-bottom:2em\"")572 + (id != null ? " id=\"" + id + "\"" : "") + ">");573 m_row = 0;574 }575 private void tableColumnStart(String label) {576 m_out.print("<th>" + label + "</th>");577 }578 private void titleRow(String label, int cq) {579 titleRow(label, cq, null);580 }581 private void titleRow(String label, int cq, String id) {582 m_out.print("<tr");583 if (id != null) {584 m_out.print(" id=\"" + id + "\"");585 }586 m_out.println("><th colspan=\"" + cq + "\">" + label + "</th></tr>");587 m_row = 0;588 }589 /** Starts HTML stream */590 protected void startHtml(PrintWriter out) {591 out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");592 out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");593 out.println("<head>");594 out.println("<title>TestNG Report</title>");595 out.println("<style type=\"text/css\">");596 out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");597 out.println("td,th {border:1px solid #009;padding:.25em .5em}");598 out.println(".result th {vertical-align:bottom}");599 out.println(".param th {padding-left:1em;padding-right:1em}");600 out.println(".param td {padding-left:.5em;padding-right:2em}");601 out.println(".stripe td,.stripe th {background-color: #E6EBF9}");602 out.println(".numi,.numi_attn {width : 18%}");603 out.println(".numi2,.numi2_attn {width : 8%}");604 out.println(".total td {font-weight:bold}");605 out.println(".passedodd td {background-color: #0A0}");606 out.println(".passedeven td {background-color: #3F3}");607 out.println(".skippedodd td {background-color: #CCC}");608 out.println(".skippedodd td {background-color: #DDD}");609 out.println(".failedodd td,.numi_attn {background-color: #F33}");610 out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}");611 out.println(".stacktrace {white-space:pre;font-family:monospace}");612 out.println(".totop {font-size:60%;text-align:center;border-bottom:2px solid #000}");613 out.println("</style>");614 out.println("</head>");615 out.println("<body>");616 }617 /** Finishes HTML stream */618 protected void endHtml(PrintWriter out) {619 out.println("<center> Report Customized By Jay Mukul </center>");620 out.println("</body></html>");621 }622 // ~ Inner Classes --------------------------------------------------------623 /** Arranges methods by classname and method name */624 private class TestSorter implements Comparator<IInvokedMethod> {625 // ~ Methods626 // -------------------------------------------------------------...
Source:ExcelReport.java
...213 ReportMap<List<String>> fourthReport = new ReportMap<List<String>>(ReportSheetNames.DEFECTREPORT.getName(), lstDefectReports, 1);214 fullReportMap.add(fourthReport);215 216 //Changing the titles of the Defect Report217 BaseReport<List<String>> bR = (BaseReport<List<String>>)fullReportMap.get(fullReportMap.size()-1).getGeneratedReport().iterator().next();218 List<String> lsTitles = Arrays.asList(new String[]{"Class Name","Method/Testcase id","Test Description","Group[s]", "Time taken", "Link", "Error Message", "Error Details"});219 bR.setColTitles(lsTitles);220 // logger.exiting();221 }222 223 /**224 * Generates all summarized counts for various reports225 * @param suites226 */227 private void generateSummaryData(List<ISuite> suites){228 // logger.entering(suites);229 SummarizedData tempSuite = null ;230 SummarizedData tempTest ;231 SummarizedData tempGroups = null;232 this.generateTestCaseResultData(suites);233 234 //Generating Group Summary data235 for (ISuite suite : suites){236 tempSuite = new SummarizedData();237 tempSuite.setsName(suite.getName());238 Map<String, ISuiteResult> allResults = suite.getResults();239 Map<String, Collection<ITestNGMethod>> tempGroupMethodMap = suite.getMethodsByGroups();240 for (String sGroupName : tempGroupMethodMap.keySet()){241 242 tempGroups = new SummarizedData();243 tempGroups.setsName(sGroupName);244 tempGroups.incrementiTotal(tempGroupMethodMap.get(sGroupName).size());245 246 for (TestCaseResult tr : allTestsResults){247 if(tr.getGroup().contains(sGroupName)){248 tempGroups.incrementCount(tr.getStatus());249 tempGroups.incrementDuration(tr.getDurationTaken());250 }251 }252 tempGroups.setiTotal(tempGroups.getiPassedCount()+tempGroups.getiFailedCount()+253 tempGroups.getiSkippedCount());254 lGroups.add(tempGroups);255 }256 257 //Generating Test summary data258 for (ISuiteResult testResult : allResults.values()){259 ITestContext testContext = testResult.getTestContext(); 260 tempTest = new SummarizedData();261 tempTest.setsName(testContext.getName());262 tempTest.setiFailedCount(testContext.getFailedTests().size());263 tempTest.setiPassedCount(testContext.getPassedTests().size());264 tempTest.setiSkippedCount(testContext.getSkippedTests().size());265 tempTest.setiTotal(tempTest.getiPassedCount()+tempTest.getiFailedCount()+tempTest.getiSkippedCount());266 tempTest.setlRuntime(testContext.getEndDate().getTime() - testContext.getStartDate().getTime());267 268 lTests.add(tempTest);269 }270 //Generating Suite Summary data271 for (SummarizedData test : lTests){272 273 tempSuite.setiPassedCount(test.getiPassedCount() + tempSuite.getiPassedCount());274 tempSuite.setiFailedCount(test.getiFailedCount() + tempSuite.getiFailedCount());275 tempSuite.setiSkippedCount(tempSuite.getiSkippedCount() + test.getiSkippedCount());276 tempSuite.setiTotal(tempSuite.getiPassedCount()+tempSuite.getiFailedCount()+tempSuite.getiSkippedCount());277 tempSuite.setlRuntime(test.getlRuntime()+tempSuite.getlRuntime());278 }279 lSuites.add(tempSuite);280 281 282 } 283 284 Collections.sort(lGroups);285 Collections.sort(lTests);286 // logger.exiting();287 } 288 289 /**290 * Method to generate array of all results of all testcases that were run in a suite291 * Output : Populates the allTestsResults arraylist with results and info for all test methods.292 */293 private void generateTestCaseResultData(List<ISuite> suites){294 // logger.entering();295 for (ISuite suite : suites){296 297 Map<String, ISuiteResult> allResults = suite.getResults();298 299 for (ISuiteResult testResult : allResults.values()){300 301 ITestContext testContext = testResult.getTestContext();302 303 IResultMap passedResultMap = testContext.getPassedTests();304 IResultMap failedResultMap = testContext.getFailedTests();305 IResultMap skippedResultMap = testContext.getSkippedTests();306 307 this.allTestsResults.addAll(this.createResultFromMap(passedResultMap));308 this.allTestsResults.addAll(this.createResultFromMap(failedResultMap));309 this.allTestsResults.addAll(this.createResultFromMap(skippedResultMap));310 }311 } 312 // logger.exiting();313 } 314 315 /**316 * Generates individual TestCase Results based on map of passed, failed and skipped methods317 * Returns the list of TestCaseResult objects generated.318 */319 private List<TestCaseResult> createResultFromMap(IResultMap resultMap){320 // logger.entering(resultMap);321 List<TestCaseResult> statusWiseResults = new ArrayList<TestCaseResult>();322 323 for (ITestResult singleMethodResult : resultMap.getAllResults()){324 TestCaseResult tcresult1 = new TestCaseResult();325 tcresult1.setITestResultobj(singleMethodResult);326 statusWiseResults.add(tcresult1);327 328 }329 Collections.sort(statusWiseResults);330 // logger.exiting(statusWiseResults);331 return statusWiseResults;332 }333 /**334 * Generates class based summary and the basis for Detailed groupwise summary report335 */336 private void generateTCBasedData(ArrayList<TestCaseResult> allTestsList ){337 // logger.entering(allTestsList);338 SummarizedData tempClass = null, tempGroupClass = null ;339 Map<String, SummarizedData> mpClassData = new HashMap<String, SummarizedData>();340 341 for (TestCaseResult tcResult : allTestsList){342 343 //Segregating for class data344 String sTempClassName = tcResult.getClassName();345 346 //If class not already added to Class data, then create new ClassObject exists347 if (!mpClassData.containsKey(sTempClassName)){348 tempClass = new SummarizedData();349 tempClass.setsName(sTempClassName);350 351 }else{352 tempClass = mpClassData.get(sTempClassName);353 }354 355 //Adding test to total count356 tempClass.incrementiTotal();357 358 //Adding all groups to map359 for (String sGroup : tcResult.getGroup()){360 361 //Forming a key for the GroupClass map which is <GroupName><ClassName>362 String sGroupClassName = sGroup+sTempClassName;363 if (!mpGroupClassData.containsKey(sGroupClassName)){364 tempGroupClass = new SummarizedData();365 tempGroupClass.setsName(sTempClassName);366 367 }else368 tempGroupClass = mpGroupClassData.get(sGroupClassName);369 370 tempGroupClass.incrementiTotal();371 tempGroupClass.incrementCount(tcResult.getStatus());372 tempGroupClass.incrementDuration(tcResult.getDurationTaken());373 mpGroupClassData.put(sGroupClassName, tempGroupClass);374 }375 376 377 //Segregating for detailed Testcase Status wise data378 List<String> str = new ArrayList<String>();379 str.add(tcResult.getClassName());380 str.add(tcResult.getMethodName());381 str.add(tcResult.getTestDesc());382 str.add(tcResult.getGroup().toString());383 str.add(String.valueOf(tcResult.getDurationTaken()));384 str.add(tcResult.getsslink());385 386 //Based on status, incrementing class count and adding str to correct387 //list for TC detailed report388 switch (tcResult.getStatus()){389 case ITestResult.FAILURE : {390 tcFailedData.add(str);391 //For failed cases adding data for defect description sheet392 for (int iErrorCount = 0; iErrorCount < tcResult.getError().size(); iErrorCount++){393 List<String> tmpList = new ArrayList<String>();394 tmpList.addAll(0, str);395 tmpList.add(tcResult.getDefect().get(iErrorCount));396 tmpList.add(tcResult.getError().get(iErrorCount));397 tcDefectData.add(tmpList);398 }399 break;400 }401 case ITestResult.SUCCESS : {402 tcPassedData.add(str);403 break;404 }405 case ITestResult.SKIP : {406 tcSkippedData.add(str);407 break;408 }409 }410 tempClass.incrementCount(tcResult.getStatus());411 //Add to the total runtime of the class412 tempClass.setlRuntime(tempClass.getlRuntime()+tcResult.getDurationTaken()); 413 mpClassData.put(sTempClassName, tempClass);414 } 415 SummarizedData[] ps = new SummarizedData[mpClassData.size()];416 lClasses = Arrays.asList(mpClassData.values().toArray(ps));417 Collections.sort(lClasses);418 // logger.exiting();419 }420}...
Source:ExtentReporterN.java
...58//Parent Class//Status//Both parent test and child test59private void buildTestNodes(IResultMap tests, LogStatus status){60 ExtentTest test;61 //Results are greater than 0 62 if (tests.size()>0) {//size will get actual of the string63 for (ITestResult result : tests.getAllResults()) {64 //returns the method(What is the method) and method name(ex. Homepage login) 65 test = extent.startTest(result.getMethod().getMethodName());66 //How long it took67 test.setStartedTime(getTime(result.getStartMillis()));68 test.setEndedTime(getTime(result.getEndMillis()));69 70 //Going through all of the results and organize the passes, skipped, failed along with time71 for(String group : result.getMethod().getGroups())72 //73 test.assignCategory(group);74 //To generated it is null75 if(result.getThrowable() !=null) {76 //Login an error
...
Source:ExtentReportListenClass.java
...66 }67 68 private void buildTestNodes(IResultMap tests, LogStatus status) {69 ExtentTest test;70 if (tests.size() > 0) {71 for (ITestResult result : tests.getAllResults()) {72 test = extent.startTest(result.getMethod().getMethodName());73 System.out.println(result.getMethod().getMethodName());74 // test.setStartedTime(getTime(result.getStartMillis()));75 //test.setEndedTime(getTime(result.getEndMillis()));76 for (String group : result.getMethod().getGroups())77 test.assignCategory(group);78 if (result.getThrowable() != null) {79 test.log(status, result.getThrowable());80 } else {81 test.log(status, "Test " + status.toString().toLowerCase()82 + "ed");83 }84 extent.endTest(test);...
Source:ExtentReporterListener.java
...43 extent.close();44 }45 private void buildTestNodes(IResultMap tests, LogStatus status) {46 ExtentTest test;47 if (tests.size() > 0) {48 for (ITestResult result : tests.getAllResults()) {49 test = extent.startTest(result.getMethod().getMethodName());50 test.setStartedTime(getTime(result.getStartMillis()));51 test.setEndedTime(getTime(result.getEndMillis()));52 for (String group : result.getMethod().getGroups())53 test.assignCategory(group);54 if (result.getThrowable() != null) {55 test.log(status, result.getThrowable());56 } else {57 test.log(status, "Test " + status.toString().toLowerCase() + "ed");58 }59 extent.endTest(test);60 }61 }...
Source:ExtentReportListener.java
...36 extent.close();37 }38 private void buildTestNodes(IResultMap tests, LogStatus status) {39 ExtentTest test;40 if (tests.size() > 0) {41 for (ITestResult result : tests.getAllResults()) {42 test = extent.startTest(result.getMethod().getMethodName());43 test.setStartedTime(getTime(result.getStartMillis()));44 test.setEndedTime(getTime(result.getEndMillis()));45 for (String group : result.getMethod().getGroups())46 test.assignCategory(group);47 if (result.getThrowable() != null) {48 test.log(status, result.getThrowable());49 } else {50 test.log(status, "Test " + status.toString().toLowerCase()51 + "ed");52 }53 extent.endTest(test);54 }...
Source:ExtentReporterNG.java
...40 extent.close();41 }42 private void buildTestNodes(IResultMap tests, LogStatus status) {43 ExtentTest test;44 if (tests.size() > 0) {45 for (ITestResult result : tests.getAllResults()) {46 test = extent.startTest(result.getMethod().getMethodName());47 test.setStartedTime(getTime(result.getStartMillis()));48 test.setEndedTime(getTime(result.getEndMillis()));49 for (String group : result.getMethod().getGroups())50 test.assignCategory(group);51 if (result.getThrowable() != null) {52 test.log(status, result.getThrowable());53 } else {54 test.log(status, "Test " + status.toString().toLowerCase()55 + "ed");56 }57 extent.endTest(test);58 }...
Source:IResultMap.java
...8 public Set<ITestResult> getAllResults();9 public void removeResult(ITestNGMethod m);10 public void removeResult(ITestResult r);11 public Collection<ITestNGMethod> getAllMethods();12 public int size();13}...
size
Using AI Code Generation
1import org.testng.ITestContext2import org.testng.ITestResult3import org.testng.TestListenerAdapter4class MyListener extends TestListenerAdapter {5 void onTestSuccess(ITestResult tr) {6 }7 void onTestFailure(ITestResult tr) {8 }9 void onTestSkipped(ITestResult tr) {10 }11 void onFinish(ITestContext testContext) {12 println "Failed tests: " + testContext.failedTests.size()13 println "Skipped tests: " + testContext.skippedTests.size()14 println "Passed tests: " + testContext.passedTests.size()15 }16}17class TestNGTest {18 void test1() {19 }20 void test2() {21 }22 void test3() {23 }24}
size
Using AI Code Generation
1package org.testng;2import org.testng.xml.XmlSuite;3import java.util.ArrayList;4import java.util.List;5import java.util.Map;6public class IResultMap implements IAttributes {7 private static final long serialVersionUID = 1L;8 private Map<String, ITestNGMethod> m_methods = Maps.newHashMap();9 private Map<String, String> m_attributes = Maps.newHashMap();10 public IResultMap() {}11 public void addResult(ITestNGMethod tm, ITestResult tr) {12 m_methods.put(tm.getMethodName(), tm);13 tm.addResult(tr, this);14 }15 public void removeResult(ITestNGMethod tm) {16 m_methods.remove(tm.getMethodName());17 }18 public int size() {19 return m_methods.size();20 }21 public Collection<ITestResult> getAllResults() {22 List<ITestResult> result = Lists.newArrayList();23 for (ITestNGMethod tm : m_methods.values()) {24 result.addAll(tm.getAllResults());25 }26 return result;27 }28 public Collection<ITestNGMethod> getAllMethods() {29 return m_methods.values();30 }31 public ITestNGMethod getMethod(String methodName) {32 return m_methods.get(methodName);33 }34 public void setAttribute(String name, String value) {35 m_attributes.put(name, value);36 }37 public String getAttribute(String name) {38 return m_attributes.get(name);39 }40 public Set<String> getAttributeNames() {41 return m_attributes.keySet();42 }43 public Object removeAttribute(String name) {44 return m_attributes.remove(name);45 }46 public String toString() {47 StringBuilder result = new StringBuilder();48 for (ITestNGMethod tm : m_methods.values()) {49 result.append(tm).append("50");51 }52 return result.toString();53 }54 public void addAll(IResultMap other) {55 m_methods.putAll(other.m_methods);56 }57 public void addAll(Collection<ITestNGMethod> methods) {58 for (ITestNGMethod tm : methods) {59 m_methods.put(tm.getMethodName(), tm);60 }61 }62 public IResultMap copy() {
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!!