Best Testng code snippet using org.testng.Interface ISuite.getName
Source:MyReporterListener.java  
...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        // -------------------------------------------------------------627        /** Arranges methods by classname and method name */628        public int compare(IInvokedMethod o1, IInvokedMethod o2) {629            // System.out.println("Comparing " + o1.getMethodName() + " " +630            // o1.getDate()631            // + " and " + o2.getMethodName() + " " + o2.getDate());632            return (int) (o1.getDate() - o2.getDate());633            // int r = ((T) o1).getTestClass().getName().compareTo(((T)634            // o2).getTestClass().getName());635            // if (r == 0) {636            // r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());637            // }638            // return r;639        }640    }641}...Source:AbstractChainedListener.java  
...60    61    Set<String> interceptor = Collections.synchronizedSet(new HashSet<String>());62    @Override63    public void onConfigurationSuccess(ITestResult itr) {64        configSuccess.add(itr.getName());65    }66    @Override67    public void onConfigurationFailure(ITestResult itr) {68        configFailure.add(itr.getName());69    }70    @Override71    public void onConfigurationSkip(ITestResult itr) {72        configSkipped.add(itr.getName());73    }74    // @Override omitted to avoid interface conflict75    public void beforeConfiguration(ITestResult tr) {76        beforeConfig.add(tr.getName());77    }78    79    @Override80    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {81        if (method.getTestMethod().isBeforeMethodConfiguration()) {82            beforeMethodBefore.add(testResult.getName());83        } else if (method.isTestMethod()) {84            testMethodBefore.add(testResult.getName());85        } else if (method.getTestMethod().isAfterMethodConfiguration()) {86            afterMethodBefore.add(testResult.getName());87        }88    }89    @Override90    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {91        if (method.getTestMethod().isBeforeMethodConfiguration()) {92            beforeMethodAfter.add(testResult.getName());93        } else if (method.isTestMethod()) {94            testMethodAfter.add(testResult.getName());95        } else if (method.getTestMethod().isAfterMethodConfiguration()) {96            afterMethodAfter.add(testResult.getName());97        }98    }99    @Override100    public void onBeforeClass(ITestClass testClass) {101        beforeClass.add(testClass.getRealClass().getSimpleName());102    }103    @Override104    public void onAfterClass(ITestClass testClass) {105        afterClass.add(testClass.getRealClass().getSimpleName());106    }107    @Override108    public void onTestStart(ITestResult result) {109        testStarted.add(result.getName());110    }111    @Override112    public void onTestSuccess(ITestResult result) {113        testSuccess.add(result.getName());114    }115    @Override116    public void onTestFailure(ITestResult result) {117        testFailure.add(result.getName());118    }119    @Override120    public void onTestSkipped(ITestResult result) {121        testSkipped.add(result.getName());122    }123    @Override124    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {125        testCurved.add(result.getName());126    }127    @Override128    public void onStart(ITestContext context) {129        testsBegun.add(context.getName());130    }131    @Override132    public void onFinish(ITestContext context) {133        testsEnded.add(context.getName());134    }135    @Override136    public void onStart(ISuite suite) {137        suiteBegun.add(suite.getName());138    }139    @Override140    public void onFinish(ISuite suite) {141        suiteEnded.add(suite.getName());142    }143    @SuppressWarnings("rawtypes")144    @Override145    public void transform(ITestAnnotation annotation, Class testClass, Constructor testCtor,146                    Method testMethod) {147        148        if (testClass != null) {149            xformTest.add("class: " + testClass.getSimpleName());150        } else if (testCtor != null) {151            xformTest.add("ctor: " + testCtor.getName());152        } else {153            xformTest.add("method: " + testMethod.getName());154        }155    }156    @SuppressWarnings("rawtypes")157    // @Override omitted to avoid interface conflict158    public void transform(IConfigurationAnnotation annotation, Class testClass,159                    Constructor testCtor, Method testMethod) {160        161        if (testClass != null) {162            xformConfig.add("class: " + testClass.getSimpleName());163        } else if (testCtor != null) {164            xformConfig.add("ctor: " + testCtor.getName());165        } else {166            xformConfig.add("method: " + testMethod.getName());167        }168    }169    // @Override omitted to avoid interface conflict170    public void transform(IDataProviderAnnotation annotation, Method method) {171        xformProvider.add("method: " + method.getName());172    }173    // @Override omitted to avoid interface conflict174    public void transform(IFactoryAnnotation annotation, Method method) {175        if (method != null) {176            xformFactory.add("method: " + method.getName());177        } else {178            xformFactory.add("ctor: (unknown)");179        }180    }181    @SuppressWarnings("rawtypes")182    // @Override omitted to avoid interface conflict183    public void transform(IListenersAnnotation annotation, Class testClass) {184        xformListeners.add("class: " + testClass.getSimpleName());185    }186    187    @Override188    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {189        interceptor.add(context.getName());190        return methods;191    }192}...Source:Listener.java  
...46	// This belongs to ISuiteListener and will execute before the Suite start4748	public void onStart(ISuite arg0) {4950		Reporter.log("About to begin executing Suite " + arg0.getName(), true);5152	}5354	// This belongs to ISuiteListener and will execute, once the Suite is finished5556	public void onFinish(ISuite arg0) {5758		Reporter.log("About to end executing Suite " + arg0.getName(), true);5960	}6162	// This belongs to ITestListener and will execute before starting of Test63	// set/batch6465	public void onStart(ITestContext arg0) {6667		Reporter.log("About to begin executing Test " + arg0.getName(), true);6869	}7071	// This belongs to ITestListener and will execute, once the Test set/batch is72	// finished7374	public void onFinish(ITestContext arg0) {7576		Reporter.log("Completed executing test " + arg0.getName(), true);7778	}7980	// This belongs to ITestListener and will execute only when the test is pass8182	public void onTestSuccess(ITestResult arg0) {8384		// This is calling the printTestResults method8586		printTestResults(arg0);8788	}8990	// This belongs to ITestListener and will execute only on the event of fail test9192	public void onTestFailure(ITestResult arg0) {9394		// This is calling the printTestResults method9596		printTestResults(arg0);9798	}99100	// This belongs to ITestListener and will execute before the main test start101	// (@Test)102103	public void onTestStart(ITestResult arg0) {104105		System.out.println("The execution of the main test starts now");106107	}108109	// This belongs to ITestListener and will execute only if any of the main110	// test(@Test) get skipped111112	public void onTestSkipped(ITestResult arg0) {113114		printTestResults(arg0);115116	}117118	// This is just a piece of shit, ignore this119120	public void onTestFailed_But_Within_Success_Percentage(ITestResult arg0) {121122	}123124	// This is the method which will be executed in case of test pass or fail125126	// This will provide the information on the test127128	private void printTestResults(ITestResult result) {129130		Reporter.log("Test Method resides in " + result.getTestClass().getName(), true);131132		if (result.getParameters().length != 0) {133134			String params = null;135136			for (Object parameter : result.getParameters()) {137138				params += parameter.toString() + ",";139140			}141142			Reporter.log("Test Method had the following parameters : " + params, true);143144		}
...Source:SuiteFixtureListener.java  
...68            // push exception up through TestNG ISuiteListener interface69            throw new RuntimeException( "Failed to parse resource located at " + wmtsURI, ex );70        }71        if ( null != doc ) {72            suite.setAttribute( SuiteAttribute.TEST_SUBJECT.getName(), doc );73            suite.setAttribute( SuiteAttribute.LAYER_INFO.getName(), parseLayerInfo( doc ) );74        }75    }76}...Source:ListenersUtils.java  
...9import org.testng.ITestListener;10import org.testng.ITestResult;11public class ListenersUtils implements ITestListener, ISuiteListener, IInvokedMethodListener {12	// Log4J interface13	public static Logger logName = LogManager.getLogger(ListenersUtils.class.getName());14	public void onStart(ITestContext result) {15		System.out.println("<-- NG Listener : onStart Start of Suite --> ");16		System.out.println(".getSuite().getName() = " + result.getSuite().getName());17//		System.out.println(".getClass().getName() = " + result.getClass().getName());18		19		logName.info("<-- NG Listener : onStart Start of Suite --> " + result.getSuite().getName());20		21		22	}23	public  void onTestStart(ITestResult result) {24		 System.out.println("<-- NG Listener : onTestStart -->"+ result.getName());25		System.out.println("<-- NG Listener : onTestStart -->");26//		System.out.println(".getSuite().getName() = " + result.getClass().getName());27		logName.info("<-- NG Listener : onTestStart -->" + result.getName());28	}29	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {30		System.out.println("<-- NG Listener : onTestFailedButWithinSuccessPercentage -->");31		logName.warn("<-- NG Listener : onTestFailedButWithinSuccessPercentage -->" + result.getName());32	}33	public void onTestFailure(ITestResult result) {34		System.out.println("<-- NG Listener : onTestFailure -->");35		logName.error("<-- NG Listener : onTestFailure -->" + result.getName());36	}37	public void onTestSkipped(ITestResult result) {38		System.out.println("<-- NG Listener : onTestSkipped -->");39		logName.warn("<-- NG Listener : onTestSkipped -->" + result.getName());40	}41	public void onTestSuccess(ITestResult result) {42		System.out.println("<-- NG Listener : onTestSuccess -->");43		logName.info("<-- NG Listener : onTestSuccess -->" + result.getName());44	}45	public void onFinish(ITestContext result) {46		System.out.println("<-- NG Listener : onFinish -->");47		logName.info("<-- NG Listener : onFinish -->" + result.getSuite());48	}49	@Override50	public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {51		// TODO Auto-generated method stub52		53	}54	@Override55	public void afterInvocation(IInvokedMethod method, ITestResult testResult) {56		// TODO Auto-generated method stub57		...Source:Guru99Reporter.java  
...25            for (String key : keys) {26             //The Context object of current result27            ITestContext context = results.get(key).getTestContext();28            //Print Suite detail in Console29             System.out.println("Suite Name->"+context.getName()30                    + "::Report output Ditectory->"+context.getOutputDirectory()31                     +"::Suite Name->"+ context.getSuite().getName()32                     +"::Start Date Time for execution->"+context.getStartDate()33                     +"::End Date Time for execution->"+context.getEndDate());34            35             //Get Map for only failed test cases36            IResultMap resultMap = context.getFailedTests();37            //Get method detail of failed test cases38            Collection<ITestNGMethod> failedMethods = resultMap.getAllMethods();39            //Loop one by one in all failed methods40            System.out.println("--------FAILED TEST CASE---------");41            for (ITestNGMethod iTestNGMethod : failedMethods) {42                //Print failed test cases detail43                System.out.println("TESTCASE NAME->"+iTestNGMethod.getMethodName()44                        +"\nDescription->"+iTestNGMethod.getDescription()45                        +"\nPriority->"+iTestNGMethod.getPriority()...Source:TestNGListeners.java  
...32    You can implement more listener interfaces in your existing class and add implemented methods33        */34   //adding unimplemented methods of the interfaces35   public void onTestStart(ITestResult result){36       System.out.print("**********************Test Started *********************"+result.getName());37   }38   public void onTestFailure(ITestResult result){39      System.out.print("**********************Test Failed *********************"+result.getName());40   }41   public void onTestSkipped(ITestResult result){42      System.out.print("**********************Test Test Skipped *********************"+result.getName());43   }44   public void onTestFailedButWithSuccessPercentage(ITestNGListener result) {45   }46   public void onFinish(ITestResult context) {47      System.out.print("**********************Tests Completed *********************"+context.getName());48   }49   @Override50   public void onStart(ISuite suite) {51   }52   @Override53   public void onFinish(ISuite suite) {54   }55}...Source:SuiteListener.java  
...28	 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)29	 */30	@Override31	public void onStart(ISuite arg0) {32		log.info("Suite Name :" + arg0.getName() + " - Start");33	}34	/*35	 * (non-Javadoc)36	 * 37	 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)38	 */39	@Override40	public void onFinish(ISuite arg0) {41		log.info("Suite Name :" + arg0.getName() + " - End");42		log.info("********Results*******");43	}44}...getName
Using AI Code Generation
1import org.testng.ISuite;2import org.testng.ISuiteListener;3public class MySuiteListener implements ISuiteListener {4   public void onStart(ISuite arg0) {5      System.out.println("Suite name is : " + arg0.getName());6   }7   public void onFinish(ISuite arg0) {8      System.out.println("Suite " + arg0.getName() + " has finished");9   }10}11import org.testng.ISuite;12import org.testng.ISuiteListener;13import org.testng.xml.XmlSuite;14public class MySuiteListener implements ISuiteListener {15   public void onStart(ISuite arg0) {16      XmlSuite suite = arg0.getXmlSuite();17      System.out.println("Suite name is : " + suite.getName());18      System.out.println("Suite Thread Count is : " + suite.getThreadCount());19   }20   public void onFinish(ISuite arg0) {21      System.out.println("Suite " + arg0.getName() + " has finished");22   }23}24import org.testng.ISuite;25import org.testng.ISuiteListener;26public class MySuiteListener implements ISuiteListener {27   public void onStart(ISuite arg0) {28      System.out.println("Suite name is : " + arg0.getName());29      System.out.println("Suite Output Directory is : " + arg0.getOutputDirectory());30   }31   public void onFinish(ISuite arg0) {32      System.out.println("Suite " + arg0.getName() + " has finished");33   }34}35import org.testng.ISuite;36import org.testng.ISuiteListener;37public class MySuiteListener implements ISuiteListener {38   public void onStart(ISuite arg0) {39      System.out.println("Suite name is : " + arg0.getName());40      System.out.println("Suite Host is : " + arg0.getHost());41   }42   public void onFinish(ISuite arg0) {43      System.out.println("Suite " + arg0.getName() + " has finished");44   }45}getName
Using AI Code Generation
1String suiteName = suite.getName();2XmlSuite suiteXml = suite.getXmlSuite();3Map results = suite.getResults();4String outputDir = suite.getOutputDirectory();5String parameter = suite.getParameter("param");6String host = suite.getHost();7String parallel = suite.getParallel();8long timeOut = suite.getTimeOut();9XmlSuite xmlSuite = suite.getXmlSuite();10long startedTime = suite.getStartedTime();11long endedTime = suite.getEndedTime();12Collection allMethods = suite.getAllMethods();13Collection allInvokedMethods = suite.getAllInvokedMethods();14Collection excludedMethods = suite.getExcludedMethods();15Collection skippedConfigurations = suite.getSkippedConfigurations();16Collection skippedTests = suite.getSkippedTests();getName
Using AI Code Generation
1String suiteName = suite.getName();2System.out.println("The name of the suite is " + suiteName);3import org.testng.ISuite;4import org.testng.ISuiteListener;5public class SuiteListener implements ISuiteListener {6public void onStart(ISuite suite) {7long startTime = suite.getStartTime();8System.out.println("The start time of the suite is " + startTime);9}10public void onFinish(ISuite suite) {11}12}13import org.testng.ISuite;14import org.testng.ISuiteListener;15public class SuiteListener implements ISuiteListener {16public void onStart(ISuite suite) {17}18public void onFinish(ISuite suite) {19long endTime = suite.getEndTime();20System.out.println("The end time of the suite is " + endTime);21}22}23In this example, we will see how to get the test results of a test suite in TestNG. The test results of a test suite is the collection of test results of all the tests in the suite. We can get this collection using getResults() method of org.testngTestNG 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!!
