Best Testng code snippet using org.testng.Interface ITestNGMethod.getMethodName
Source:MyReporterListener.java  
...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:IDEATestNGRemoteListener.java  
...53                break;54              }55            }56            if (!found) {57              final String fullEscapedMethodName = escapeName(getShortName(method.getTestClass().getName()) + "/" + method.getMethodName());58              myPrintStream.println("##teamcity[testStarted name=\'" + fullEscapedMethodName + "\']");59              myPrintStream.println("##teamcity[testIgnored name=\'" + fullEscapedMethodName + "\']");60              myPrintStream.println("##teamcity[testFinished name=\'" + fullEscapedMethodName + "\']");61              break;62            }63          }64        }65      }66    }67    catch (NoSuchMethodError ignored) {}68    for (int i = myCurrentSuites.size() - 1; i >= 0; i--) {69      onSuiteFinish(myCurrentSuites.remove(i));70    }71    myCurrentSuites.clear();72  }73  public synchronized void onConfigurationSuccess(ITestResult result, boolean start) {74    final DelegatedResult delegatedResult = createDelegated(result);75    if (start) {76      onConfigurationStart(delegatedResult);77    }78    onConfigurationSuccess(delegatedResult);79  }80  public synchronized void onConfigurationFailure(ITestResult result, boolean start) {81    final DelegatedResult delegatedResult = createDelegated(result);82    if (start) {83      onConfigurationStart(delegatedResult);84    }85    onConfigurationFailure(delegatedResult);86  }87  public synchronized void onConfigurationSkip(ITestResult itr) {}88  public synchronized void onTestStart(ITestResult result) {89    onTestStart(createDelegated(result));90  }91  public synchronized void onTestSuccess(ITestResult result) {92    onTestFinished(createDelegated(result));93  }94  public synchronized void onTestFailure(ITestResult result) {95    onTestFailure(createDelegated(result));96  }97  public synchronized void onTestSkipped(ITestResult result) {98    onTestSkipped(createDelegated(result));99  }100  public synchronized void onTestFailedButWithinSuccessPercentage(ITestResult result) {101    final Throwable throwable = result.getThrowable();102    if (throwable != null) {103      throwable.printStackTrace();104    }105    onTestSuccess(result);106  }107  public synchronized void onStart(ITestContext context) {}108  public synchronized void onFinish(ITestContext context) {}109  public void onTestStart(ExposedTestResult result) {110   onStartWithParameters(result, false);111  }112  public void onStartWithParameters(ExposedTestResult result, boolean config) {113    final Object[] parameters = result.getParameters();114    final String qualifiedName = result.getClassName() + result.getDisplayMethodName();115    Integer invocationCount = myInvocationCounts.get(qualifiedName);116    if (invocationCount == null) {117      invocationCount = 0;118    }119    Integer normalizedIndex = normalizeInvocationCountInsideIncludedMethods(invocationCount, result);120    final String paramString = getParamsString(parameters, config, normalizedIndex);121    onTestStart(result, paramString, normalizedIndex, config);122    myInvocationCounts.put(qualifiedName, invocationCount + 1);123  }124  private static Integer normalizeInvocationCountInsideIncludedMethods(Integer invocationCount, ExposedTestResult result) {125    List<Integer> includeMethods = result.getIncludeMethods();126    if (includeMethods == null || invocationCount >= includeMethods.size()) {127      return invocationCount;128    }129    return includeMethods.get(invocationCount);130  }131  public void onConfigurationStart(ExposedTestResult result) {132    onStartWithParameters(result, true);133  }134  public void onConfigurationSuccess(ExposedTestResult result) {135    onTestFinished(result);136  }137  public void onConfigurationFailure(ExposedTestResult result) {138    onTestFailure(result);139  }140  141  public boolean onSuiteStart(String classFQName, boolean provideLocation) {142    return onSuiteStart(Collections.singletonList(classFQName), null, provideLocation);143  }144  public boolean onSuiteStart(List<String> parentsHierarchy, ExposedTestResult result, boolean provideLocation) {145    int idx = 0;146    String currentClass;147    String currentParent;148    while (idx < myCurrentSuites.size() && idx < parentsHierarchy.size()) {149      currentClass = myCurrentSuites.get(idx);150      currentParent =parentsHierarchy.get(parentsHierarchy.size() - 1 - idx);151      if (!currentClass.equals(getShortName(currentParent))) break;152      idx++;153    }154    for (int i = myCurrentSuites.size() - 1; i >= idx; i--) {155      currentClass = myCurrentSuites.remove(i);156      myPrintStream.println("##teamcity[testSuiteFinished name=\'" + escapeName(currentClass) + "\']");157    }158    for (int i = idx; i < parentsHierarchy.size(); i++) {159      String fqName = parentsHierarchy.get(parentsHierarchy.size() - 1 - i);160      String currentClassName = getShortName(fqName);161      String location = "java:suite://" + escapeName(fqName);162      if (result != null) {163        final String testName = result.getXmlTestName();164        if (fqName.equals(testName)) {165          final String fileName = result.getFileName();166          if (fileName != null) {167            location = "file://" + fileName;168          }169        }170      }171      myPrintStream.println("\n##teamcity[testSuiteStarted name =\'" + escapeName(currentClassName) +172                            (provideLocation ? "\' locationHint = \'" + location : "") + "\']");173      myCurrentSuites.add(currentClassName);174    }175    return false;176  }177  public void onSuiteFinish(String suiteName) {178    myPrintStream.println("##teamcity[testSuiteFinished name=\'" + escapeName(suiteName) + "\']");179  }180  private void onTestStart(ExposedTestResult result, String paramString, Integer invocationCount, boolean config) {181    myParamsMap.put(result, paramString);182    onSuiteStart(result.getTestHierarchy(), result, true);183    final String className = result.getClassName();184    final String methodName = result.getDisplayMethodName();185    final String location = className + "/" + result.getMethodName() + (invocationCount >= 0 ? "[" + invocationCount + "]" : "");186    myPrintStream.println("\n##teamcity[testStarted name=\'" + escapeName(getShortName(className) + "." + methodName + (paramString != null ? paramString : "")) +187                          "\' locationHint=\'java:test://" + escapeName(location) + (config ? "\' config=\'true" : "") + "\']");188  }189  public void onTestFailure(ExposedTestResult result) {190    if (!myParamsMap.containsKey(result)) {191      onTestStart(result);192    }193    Throwable ex = result.getThrowable();194    String methodName = getTestMethodNameWithParams(result);195    final Map<String, String> attrs = new LinkedHashMap<String, String>();196    attrs.put("name", methodName);197    final String failureMessage = ex != null ? ex.getMessage() : null;198    if (ex != null) {199      ComparisonFailureData notification;200      try {201        notification = ComparisonFailureData.create(ex);202      }203      catch (Throwable e) {204        notification = null;205      }206      if (notification == null) {207        try {208          notification = TestNGExpectedPatterns.createExceptionNotification(failureMessage);209        }210        catch (Throwable e) {211          notification = null;212        }213      }214      ComparisonFailureData.registerSMAttributes(notification, getTrace(ex), failureMessage, attrs, ex);215    }216    else {217      attrs.put("message", "");218    }219    myPrintStream.println();220    myPrintStream.println(MapSerializerUtil.asString("testFailed", attrs));221    onTestFinished(result);222  }223  public void onTestSkipped(ExposedTestResult result) {224    if (!myParamsMap.containsKey(result)) {225      onTestStart(result);226      mySkipped++;227    }228    myPrintStream.println("\n##teamcity[testIgnored name=\'" + escapeName(getTestMethodNameWithParams(result)) + "\']");229    onTestFinished(result);230  }231  public void onTestFinished(ExposedTestResult result) {232    final long duration = result.getDuration();233    myPrintStream.println("\n##teamcity[testFinished name=\'" +234                          escapeName(getTestMethodNameWithParams(result)) +235                          (duration > 0 ? "\' duration=\'" + duration : "") +236                          "\']");237  }238  private synchronized String getTestMethodNameWithParams(ExposedTestResult result) {239    String methodName = getShortName(result.getClassName()) + "." + result.getDisplayMethodName();240    String paramString = myParamsMap.get(result);241    if (paramString != null) {242      methodName += paramString;243    }244    return methodName;245  }246  private static String getParamsString(Object[] parameters, boolean config, int invocationCount) {247    String paramString = "";248    if (parameters.length > 0) {249      if (config) {250        Object parameter = parameters[0];251        if (parameter != null) {252          Class<?> parameterClass = parameter.getClass();253          if (ITestResult.class.isAssignableFrom(parameterClass) || ITestContext.class.isAssignableFrom(parameterClass) || Method.class.isAssignableFrom(parameterClass)) {254            try {255              paramString = "[" + parameterClass.getMethod("getName").invoke(parameter) + "]";256            }257            catch (Throwable e) {258              paramString = "";259            }260          }261          else {262            paramString = "[" + parameter.toString() + "]";263          }264        }265      }266      else {267        paramString = Arrays.deepToString(parameters);268      }269    }270    if (invocationCount > 0) {271      paramString += " (" + invocationCount + ")";272    }273    return paramString.length() > 0 ? paramString : null;274  }275  protected String getTrace(Throwable tr) {276    StringWriter stringWriter = new StringWriter();277    PrintWriter writer = new PrintWriter(stringWriter);278    tr.printStackTrace(writer);279    StringBuffer buffer = stringWriter.getBuffer();280    return buffer.toString();281  }282  protected static String getShortName(String fqName) {283    int lastPointIdx = fqName.lastIndexOf('.');284    if (lastPointIdx >= 0) {285      return fqName.substring(lastPointIdx + 1);286    }287    return fqName;288  }289  private static String escapeName(String str) {290    return MapSerializerUtil.escapeStr(str, MapSerializerUtil.STD_ESCAPER);291  }292  public interface ExposedTestResult {293    Object[] getParameters();294    String getMethodName();295    String getDisplayMethodName();296    String getClassName();297    long getDuration();298    List<String> getTestHierarchy();299    String getFileName();300    String getXmlTestName();301    Throwable getThrowable();302    List<Integer> getIncludeMethods();303  }304  protected DelegatedResult createDelegated(ITestResult result) {305    final DelegatedResult newResult = new DelegatedResult(result);306    final DelegatedResult oldResult = myResults.get(newResult);307    if (oldResult != null) {308      return oldResult;309    }310    myResults.put(newResult, newResult);311    return newResult;312  }313  314  protected static class DelegatedResult implements ExposedTestResult {315    private final ITestResult myResult;316    private final String myTestName;317    public DelegatedResult(ITestResult result) {318      myResult = result;319      myTestName = calculateDisplayName();320    }321    //workaround for https://github.com/cbeust/testng/issues/1944322    private String calculateDisplayName() {323      String name = myResult.getTestName();324      if (name != null && !name.equals(myResult.getTestClass().getTestName())) {325        return name;326      }327      ITestNGMethod method = myResult.getMethod();328      ConstructorOrMethod constructorOrMethod = method.getConstructorOrMethod();329      AccessibleObject member = null;330      if (constructorOrMethod.getMethod() != null) {331        member = constructorOrMethod.getMethod();332      }333      if (constructorOrMethod.getConstructor() != null) {334        member = constructorOrMethod.getConstructor();335      }336      if (member == null) return method.getMethodName();337      Test annotation = member.getAnnotation(Test.class);338      if (annotation == null) return method.getMethodName();339      String testNameFromAnnotation = annotation.testName();340      return testNameFromAnnotation == null || testNameFromAnnotation.length() == 0 ? method.getMethodName() : testNameFromAnnotation;341    }342    public Object[] getParameters() {343      return myResult.getParameters();344    }345    public String getMethodName() {346      return myResult.getMethod().getMethodName();347    }348    public String getDisplayMethodName() {349      return myTestName;350    }351    public String getClassName() {352      return myResult.getMethod().getTestClass().getName();353    }354    public long getDuration() {355      return myResult.getEndMillis() - myResult.getStartMillis();356    }357    public List<String> getTestHierarchy() {358      final List<String> hierarchy;359      final XmlTest xmlTest = myResult.getTestClass().getXmlTest();360      if (xmlTest != null) {...Source:TestListener.java  
...29        for (int j = 0; j < failedList.size(); j++) {30            ITestResult tr = (ITestResult) failedList.get(j);31            for (int i = 0; i < method.length; i++) {32                Object[] para = tr.getParameters();33                if (tr.getMethod().getMethodName().equals(method[i].getMethodName())) {34                    if (para.length != 0) {35                        String str="";36                        for(int m=0;m<para.length;m++) {37                            if(m == para.length-1)38                                str = str+ para[m];39                            else {40                                str = str+ para[m] + " , ";41                            }42                        }43                        tr.setAttribute("value", str);44                    } else {45                        tr.setAttribute("value", "");46                    }47                    break;48                }49            }50            failedList1.add(tr);51        }52        for (int j = 0; j < passedList.size(); j++) {53            ITestResult tr = (ITestResult) passedList.get(j);54            for (int i = 0; i < method.length; i++) {55                Object[] para = tr.getParameters();56                if (tr.getMethod().getMethodName().equals(method[i].getMethodName())) {57                    if (para.length != 0) {58                        String str="";59                        for(int m=0;m<para.length;m++) {60                            if(m == para.length-1)61                                str = str+ para[m];62                            else {63                                str = str+ para[m] + ",";64                            }65                        }66                        System.out.println(str);67                        tr.setAttribute("value", str);68                    } else {69                        tr.setAttribute("value", "");70                    }...Source:Listener.java  
...194	// This will return method names to the calling function195196	private String returnMethodName(ITestNGMethod method) {197198		return method.getRealClass().getSimpleName() + "." + method.getMethodName();199200	}201202}
...Source:DefaultMethodTest.java  
...11  public void testDefaultShouldRun() {12    ITestClass testClass = runTestWithDefaultMethods();13    ITestNGMethod[] testMethods = testClass.getTestMethods();14    Assert.assertEquals(testMethods.length, 1);15    Assert.assertEquals(testMethods[0].getMethodName(), "defaultMethodTest");16  }17  @Test(description = "Before class default methods defined in an interface should be run")18  public void beforeClassDefaultShouldRun() {19    ITestClass testClass = runTestWithDefaultMethods();20    ITestNGMethod[] beforeClassMethods = testClass.getBeforeClassMethods();21    Assert.assertEquals(beforeClassMethods.length, 1);22    Assert.assertEquals(beforeClassMethods[0].getMethodName(), "beforeClassRun");23  }24  @Test(description = "After class default methods defined in an interface should be run")25  public void afterClassDefaultShouldRun() {26    ITestClass testClass = runTestWithDefaultMethods();27    ITestNGMethod[] afterClassMethods = testClass.getAfterClassMethods();28    Assert.assertEquals(afterClassMethods.length, 1);29    Assert.assertEquals(afterClassMethods[0].getMethodName(), "afterClassRun");30  }31  @Test(description = "Before method default methods defined in an interface should be run")32  public void beforeMethodDefaultShouldRun() {33    final ITestClass testClass = runTestWithDefaultMethods();34    ITestNGMethod[] beforeMethods = testClass.getBeforeTestMethods();35    Assert.assertEquals(beforeMethods.length, 1);36    Assert.assertEquals(beforeMethods[0].getMethodName(), "beforeMethodRun");37  }38  @Test(description = "After method default methods defined in an interface should be run")39  public void afterMethodDefaultShouldRun() {40    final ITestClass testClass = runTestWithDefaultMethods();41    ITestNGMethod[] afterMethods = testClass.getAfterTestMethods();42    Assert.assertEquals(afterMethods.length, 1);43    Assert.assertEquals(afterMethods[0].getMethodName(), "afterMethodRun");44  }45  private ITestClass runTestWithDefaultMethods() {46    TestNG tng = create(TestA.class);47    TestClassListener listener = new TestClassListener();48    tng.addListener(listener);49    tng.run();50    return listener.testClass;51  }52  public static class TestClassListener extends TestAndClassListener {53    private ITestClass testClass;54    @Override55    public void onBeforeClass(ITestClass testClass) {56      this.testClass = testClass;57    }...Source:Guru99Reporter.java  
...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()46                        +"\n:Date->"+new Date(iTestNGMethod.getDate()));47                48            }49        }50        }51        52    }53}...Source:Listeners.java  
...19        // TODO Auto-generated method stub20        System.out.println("onStart= "+context.getName());21        ITestNGMethod methods[] = context.getAllTestMethods();22        for ( ITestNGMethod method: methods) {23            System.out.println(method.getMethodName());24        }25    }26    @Override27    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {28        // TODO Auto-generated method stub29        System.out.println("onTestFailedButWithinSuccessPercentag= "+result.getName());30    }31    @Override32    public void onTestFailure(ITestResult result) {33        // TODO Auto-generated method stub34//screenshot code35  //response if API is failed36        System.out.println("I failed the execution "+result.getName());37    }...Source:CustomListener2.java  
...32	public void onStart(ITestContext context) {                                                //can be used for printing all the test method which will going to run...33		System.out.println("onStart: it will run before every test tag in xml file. => " + context.getName());34		ITestNGMethod methods[] = context.getAllTestMethods();35		for(ITestNGMethod method : methods) {36			System.out.println(method.getMethodName());37		}	38	}39	@Override40	public void onFinish(ITestContext context) {41		System.out.println("onFinish: it will run after every test tag in xml file. => " + context.getName());42	}43}...getMethodName
Using AI Code Generation
1import org.testng.ITestNGMethod;2import org.testng.ITestResult;3import org.testng.TestListenerAdapter;4import org.testng.annotations.Test;5public class TestNGListener extends TestListenerAdapter {6    public void onTestFailure(ITestResult tr) {7        super.onTestFailure(tr);8        System.out.println("Test Failed");9        ITestNGMethod method = tr.getMethod();10        System.out.println("Method Name: " + method.getMethodName());11    }12    public void testMethod() {13        System.out.println("Test Method");14    }15}16onTestSkipped() method17import org.testng.ITestNGMethod;18import org.testng.ITestResult;19import org.testng.TestListenerAdapter;20import org.testng.annotations.Test;21public class TestNGListener extends TestListenerAdapter {22    public void onTestSkipped(ITestResult tr) {23        super.onTestSkipped(tr);24        System.out.println("Test Skipped");25        ITestNGMethod method = tr.getMethod();26        System.out.println("Method Name: " + method.getMethodName());27    }28    public void testMethod() {29        System.out.println("Test Method");30    }31}32onTestStart() method33import org.testng.ITestNGMethod;34import org.testng.ITestResult;35import org.testng.TestListenerAdapter;36import org.testng.annotations.Test;37public class TestNGListener extends TestListenerAdapter {38    public void onTestStart(ITestResult tr) {39        super.onTestStart(tr);40        System.out.println("Test Started");41        ITestNGMethod method = tr.getMethod();42        System.out.println("Method Name: " + method.getMethodName());43    }44    public void testMethod() {45        System.out.println("Test Method");46    }47}getMethodName
Using AI Code Generation
1package com.automation;2import org.testng.ITestNGMethod;3import org.testng.annotations.Test;4public class TestNGMethod {5	public void test() {6		ITestNGMethod[] methods = this.getClass().getMethods();7		for (ITestNGMethod method : methods) {8			System.out.println(method.getMethodName());9		}10	}11}12package com.automation;13import org.testng.ITestResult;14import org.testng.annotations.Test;15public class TestNGMethod {16	public void test() {17		ITestResult result = null;18		System.out.println(result.getMethod().getMethodName());19	}20}21package com.automation;22import org.testng.ITestContext;23import org.testng.annotations.Test;24public class TestNGMethod {25	public void test() {26		ITestContext context = null;27		System.out.println(context.getName());28	}29}30package com.automation;31import org.testng.ITest;32import org.testng.annotations.Test;33public class TestNGMethod implements ITest {34	public void test() {35		System.out.println(getTestName());36	}37	public String getTestName() {38		return "test";39	}40}41package com.automation;42import org.testng.IHookCallBack;43import org.testng.IHookable;44import org.testng.ITestResult;45import org.testng.annotations.Test;46public class TestNGMethod implements IHookable {47	public void test() {48		System.out.println("test");49	}50	public void run(IHookCallBack callBack, ITestResult testResult) {51		System.out.println(testResult.getMethod().getMethodName());52	}53}54package com.automation;55import org.testng.IInvokedMethod;56import org.testng.IInvokedMethodListener;57import org.testng.ITestResult;58import org.testng.annotations.Test;59public class TestNGMethod implements IInvokedMethodListener {60	public void test() {61		System.out.println("test");62	}getMethodName
Using AI Code Generation
1package com.test;2import org.testng.ITestNGMethod;3import org.testng.annotations.Test;4public class TestingClass {5public void test1() {6ITestNGMethod testNGMethod = new ITestNGMethod() {7public int getInvocationCount() {8return 0;9}10public int getThreadPoolSize() {11return 0;12}13public boolean getEnabled() {14return false;15}16public long getTimeOut() {17return 0;18}19public boolean getIgnoreMissingDependencies() {20return false;21}22public String[] getGroups() {23return new String[0];24}25public String[] getGroupsDependedUpon() {26return new String[0];27}28public String[] getMethodsDependedUpon() {29return new String[0];30}31public String getDescription() {32return null;33}34public String getMethodName() {35return "test1";36}37public String getTestClass() {38return null;39}40public String getXmlTestName() {41return null;42}43public String getInstanceName() {44return null;45}46public String getQualifiedName() {47return null;48}49public String getBeforeGroups() {50return null;51}52public String getAfterGroups() {53return null;54}55public String getBeforeMethod() {56return null;57}58public String getAfterMethod() {59return null;60}61public String getBeforeClass() {62return null;63}64public String getAfterClass() {65return null;66}67public String getBeforeTest() {68return null;69}70public String getAfterTest() {71return null;72}73public String getBeforeSuite() {74return null;75}76public String getAfterSuite() {77return null;78}79public String getBeforeInvocation() {80return null;81}82public String getAfterInvocation() {83return null;84}85public String getBeforeTestConfiguration() {86return null;87}88public String getAfterTestConfiguration() {89return null;90}91public String getBeforeClassConfiguration() {92return null;93}94public String getAfterClassConfiguration() {95return null;96}97public String getBeforeMethodConfiguration() {98return null;99}100public String getAfterMethodConfiguration() {101return null;102}103public String getBeforeSuiteConfiguration() {104return null;105}getMethodName
Using AI Code Generation
1package com.qa.testcases;2import org.testng.ITestNGMethod;3import org.testng.annotations.Test;4public class GetMethodName {5    public void test() {6        ITestNGMethod method = new ITestNGMethod() {7            public void setEnabled(boolean enabled) {8            }9            public void setInvocationCount(int invocationCount) {10            }11            public void setInvocationNumbers(int[] numbers) {12            }13            public void setInvocationTimeOut(long timeOut) {14            }15            public void setSkipFailedInvocations(boolean skip) {16            }17            public void setThreadPoolSize(int poolSize) {18            }19            public void setRetryAnalyzerClass(Class<? extends IRetryAnalyzer> retryAnalyzer) {20            }21            public void setParameters(Object[] parameters) {22            }23            public void setParameterInvocationCount(int parameterInvocationCount) {24            }25            public void setGroups(String[] groups) {26            }27            public void setGroupsDependedUpon(String[] groups) {28            }29            public void setMethodsDependedUpon(String[] methods) {30            }31            public void setBeforeGroups(String[] beforeGroups) {32            }33            public void setAfterGroups(String[] afterGroups) {34            }35            public void setDescription(String description) {36            }37            public void setTestName(String testName) {38            }39            public void setTest(boolean isTest) {40            }41            public void setIgnoreMissingDependencies(boolean ignoreMissingDependencies) {42            }43            public void setAlwaysRun(boolean alwaysRun) {44            }45            public void setSuccessPercentage(int successPercentage) {46            }47            public void setPriority(int priority) {48            }49            public void setEnabled(boolean enabled, boolean force) {50            }51            public void setIgnoreMissingDependencies(boolean ignoreMissingDependencies, boolean force) {52            }53            public void setAlwaysRun(boolean alwaysRun, boolean force) {54            }55            public void setSuccessPercentage(int successPercentage,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!!
