Best Testng code snippet using org.testng.reporters.XMLReporterConfig.setOutputDirectory
Source:CustomTestNgReporter.java  
...63    }64    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,65                               String outputDirectory) {66        if (Utils.isStringEmpty(config.getOutputDirectory())) {67            config.setOutputDirectory(outputDirectory);68        }69        rootBuffer = new XMLStringBuffer("");70        rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS);71        writeReporterOutput(rootBuffer);72        for (int i = 0; i < suites.size(); i++) {73            writeSuite(suites.get(i).getXmlSuite(), suites.get(i));74        }75        rootBuffer.pop();76        Utils.writeUtf8File(config.getOutputDirectory(), "testng-results.xml", rootBuffer.toXML());77    }78    private void writeReporterOutput(XMLStringBuffer xmlBuffer) {79        xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT);80        List<String> output = Reporter.getOutput();81        for (String line : output) {...Source:PowerXMLReport.java  
...32	  @Override33	  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,34	      String outputDirectory) {35	    if (Utils.isStringEmpty(config.getOutputDirectory())) {36	      config.setOutputDirectory(outputDirectory);37	    }3839	    // Calculate passed/failed/skipped40	    int passed = 0;41	    int failed = 0;42	    int skipped = 0;43	    for (ISuite s : suites) {44	      for (ISuiteResult sr : s.getResults().values()) {45	        ITestContext testContext = sr.getTestContext();46	        passed += testContext.getPassedTests().size();47	        failed += testContext.getFailedTests().size();48	        skipped += testContext.getSkippedTests().size();49	      }50	    }5152	    rootBuffer = new XMLStringBuffer();53	    Properties p = new Properties();54	    p.put("passed", passed);55	    p.put("failed", failed);56	    p.put("skipped", skipped);57	    p.put("total", passed + failed + skipped);58	    rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS, p);59	    writeReporterOutput(rootBuffer);60	    for (ISuite suite : suites) {61	      writeSuite(suite.getXmlSuite(), suite);62	    }63	    rootBuffer.pop();64	    Utils.writeUtf8File(config.getOutputDirectory(), FILE_NAME, rootBuffer, null /* no prefix */);65	  }6667	  private void writeReporterOutput(XMLStringBuffer xmlBuffer) {68	    // TODO: Cosmin - maybe a <line> element isn't indicated for each line69	    xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT);70	    List<String> output = Reporter.getOutput();71	    for (String line : output) {72	      if (line != null) {73	        xmlBuffer.push(XMLReporterConfig.TAG_LINE);74	        xmlBuffer.addCDATA(line);75	        xmlBuffer.pop();76	      }77	    }78	    xmlBuffer.pop();79	  }8081	  private void writeSuite(XmlSuite xmlSuite, ISuite suite) {82	    switch (config.getFileFragmentationLevel()) {83	    case XMLReporterConfig.FF_LEVEL_NONE:84	      writeSuiteToBuffer(rootBuffer, suite);85	      break;86	    case XMLReporterConfig.FF_LEVEL_SUITE:87	    case XMLReporterConfig.FF_LEVEL_SUITE_RESULT:88	      File suiteFile = referenceSuite(rootBuffer, suite);89	      writeSuiteToFile(suiteFile, suite);90	    }91	  }9293	  private void writeSuiteToFile(File suiteFile, ISuite suite) {94	    XMLStringBuffer xmlBuffer = new XMLStringBuffer();95	    writeSuiteToBuffer(xmlBuffer, suite);96	    File parentDir = suiteFile.getParentFile();97	    if (parentDir.exists() || suiteFile.getParentFile().mkdirs()) {98	      Utils.writeFile(parentDir.getAbsolutePath(), FILE_NAME, xmlBuffer.toXML());99	    }100	  }101102	  private File referenceSuite(XMLStringBuffer xmlBuffer, ISuite suite) {103	    String relativePath = suite.getName() + File.separatorChar + FILE_NAME;104	    File suiteFile = new File(config.getOutputDirectory(), relativePath);105	    Properties attrs = new Properties();106	    attrs.setProperty(XMLReporterConfig.ATTR_URL, relativePath);107	    xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_SUITE, attrs);108	    return suiteFile;109	  }110111	  private void writeSuiteToBuffer(XMLStringBuffer xmlBuffer, ISuite suite) {112	    xmlBuffer.push(XMLReporterConfig.TAG_SUITE, getSuiteAttributes(suite));113	    writeSuiteGroups(xmlBuffer, suite);114115	    Map<String, ISuiteResult> results = suite.getResults();116	    NeXMLSuiteResultWriter suiteResultWriter = new NeXMLSuiteResultWriter(config);117	    for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {118	      suiteResultWriter.writeSuiteResult(xmlBuffer, result.getValue());119	    }120121	    xmlBuffer.pop();122	  }123124	  private void writeSuiteGroups(XMLStringBuffer xmlBuffer, ISuite suite) {125	    xmlBuffer.push(XMLReporterConfig.TAG_GROUPS);126	    Map<String, Collection<ITestNGMethod>> methodsByGroups = suite.getMethodsByGroups();127	    for (Map.Entry<String, Collection<ITestNGMethod>> entry : methodsByGroups.entrySet()) {128	      Properties groupAttrs = new Properties();129	      groupAttrs.setProperty(XMLReporterConfig.ATTR_NAME, entry.getKey());130	      xmlBuffer.push(XMLReporterConfig.TAG_GROUP, groupAttrs);131	      Set<ITestNGMethod> groupMethods = getUniqueMethodSet(entry.getValue());132	      for (ITestNGMethod groupMethod : groupMethods) {133	        Properties methodAttrs = new Properties();134	        methodAttrs.setProperty(XMLReporterConfig.ATTR_NAME, groupMethod.getMethodName());135	        methodAttrs.setProperty(XMLReporterConfig.ATTR_METHOD_SIG, groupMethod.toString());136	        methodAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, groupMethod.getRealClass().getName());137	        xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_METHOD, methodAttrs);138	      }139	      xmlBuffer.pop();140	    }141	    xmlBuffer.pop();142	  }143144	  private Properties getSuiteAttributes(ISuite suite) {145	    Properties props = new Properties();146	    props.setProperty(XMLReporterConfig.ATTR_NAME, suite.getName());147148	    // Calculate the duration149	    Map<String, ISuiteResult> results = suite.getResults();150	    Date minStartDate = new Date();151	    Date maxEndDate = null;152	    // TODO: We could probably optimize this in order not to traverse this twice153	    for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {154	      ITestContext testContext = result.getValue().getTestContext();155	      Date startDate = testContext.getStartDate();156	      Date endDate = testContext.getEndDate();157	      if (minStartDate.after(startDate)) {158	        minStartDate = startDate;159	      }160	      if (maxEndDate == null || maxEndDate.before(endDate)) {161	        maxEndDate = endDate != null ? endDate : startDate;162	      }163	    }164165	    // The suite could be completely empty166	    if (maxEndDate == null) {167	      maxEndDate = minStartDate;168	    }169	    addDurationAttributes(config, props, minStartDate, maxEndDate);170	    return props;171	  }172173	  /**174	   * Add started-at, finished-at and duration-ms attributes to the <suite> tag175	   */176	  public static void addDurationAttributes(XMLReporterConfig config, Properties attributes,177	      Date minStartDate, Date maxEndDate) {178	    SimpleDateFormat format = new SimpleDateFormat(XMLReporterConfig.getTimestampFormat());179	    TimeZone utc = TimeZone.getTimeZone("UTC");180	    format.setTimeZone(utc);181	    String startTime = format.format(minStartDate);182	    String endTime = format.format(maxEndDate);183	    long duration = maxEndDate.getTime() - minStartDate.getTime();184185	    attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime);186	    attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime);187	    attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, Long.toString(duration));188	  }189190	  private Set<ITestNGMethod> getUniqueMethodSet(Collection<ITestNGMethod> methods) {191	    Set<ITestNGMethod> result = new LinkedHashSet<>();192	    for (ITestNGMethod method : methods) {193	      result.add(method);194	    }195	    return result;196	  }197198	  // TODO: This is not the smartest way to implement the config199	  public int getFileFragmentationLevel() {200	    return config.getFileFragmentationLevel();201	  }202203	  public void setFileFragmentationLevel(int fileFragmentationLevel) {204	    config.setFileFragmentationLevel(fileFragmentationLevel);205	  }206207	  public int getStackTraceOutputMethod() {208	    return config.getStackTraceOutputMethod();209	  }210211	  public void setStackTraceOutputMethod(int stackTraceOutputMethod) {212	    config.setStackTraceOutputMethod(stackTraceOutputMethod);213	  }214215	  public String getOutputDirectory() {216	    return config.getOutputDirectory();217	  }218219	  public void setOutputDirectory(String outputDirectory) {220	    config.setOutputDirectory(outputDirectory);221	  }222223	  public boolean isGenerateGroupsAttribute() {224	    return config.isGenerateGroupsAttribute();225	  }226227	  public void setGenerateGroupsAttribute(boolean generateGroupsAttribute) {228	    config.setGenerateGroupsAttribute(generateGroupsAttribute);229	  }230231	  public boolean isSplitClassAndPackageNames() {232	    return config.isSplitClassAndPackageNames();233	  }234
...Source:XMLPassedTestReporter.java  
...30	  @Override31	  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,32	      String outputDirectory) {33	    if (Utils.isStringEmpty(config.getOutputDirectory())) {34	      config.setOutputDirectory(outputDirectory);35	    }36	    // Calculate passed/failed/skipped37	    int passed = 0;38	    int failed = 0;39	    int skipped = 0;40	    for (ISuite s : suites) {41	      for (ISuiteResult sr : s.getResults().values()) {42	        ITestContext testContext = sr.getTestContext();43	        passed += testContext.getPassedTests().size();44	        failed += testContext.getFailedTests().size();45	        skipped += testContext.getSkippedTests().size();46	      }47	    }48	    rootBuffer = new XMLStringBuffer();49	    Properties p = new Properties();50	    p.put("passed", passed);51	    p.put("failed", failed);52	    p.put("skipped", skipped);53	    p.put("total", passed + failed + skipped);54	    rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS, p);55	    writeReporterOutput(rootBuffer);56	    for (int i = 0; i < suites.size(); i++) {57	    	58	      writeSuite(suites.get(i).getXmlSuite(), suites.get(i));59	    }60	    rootBuffer.pop();61	    Utils.writeUtf8File(config.getOutputDirectory(), FILE_NAME, rootBuffer, null /* no prefix */);62	  }63	  private void writeReporterOutput(XMLStringBuffer xmlBuffer) {64	    // TODO: Cosmin - maybe a <line> element isn't indicated for each line65	    xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT);66	    List<String> output = Reporter.getOutput();67	    for (String line : output) {68	      if (line != null) {69	        xmlBuffer.push(XMLReporterConfig.TAG_LINE);70	        xmlBuffer.addCDATA(line);71	        xmlBuffer.pop();72	      }73	    }74	    xmlBuffer.pop();75	  }76	  private void writeSuite(XmlSuite xmlSuite, ISuite suite) {77	    switch (config.getFileFragmentationLevel()) {78	    case XMLReporterConfig.FF_LEVEL_NONE:79	      writeSuiteToBuffer(rootBuffer, suite);80	      break;81	    case XMLReporterConfig.FF_LEVEL_SUITE:82	    case XMLReporterConfig.FF_LEVEL_SUITE_RESULT:83	      File suiteFile = referenceSuite(rootBuffer, suite);84	      writeSuiteToFile(suiteFile, suite);85	    }86	  }87	  private void writeSuiteToFile(File suiteFile, ISuite suite) {88	    XMLStringBuffer xmlBuffer = new XMLStringBuffer();89	    writeSuiteToBuffer(xmlBuffer, suite);90	    File parentDir = suiteFile.getParentFile();91	    if (parentDir.exists() || suiteFile.getParentFile().mkdirs()) {92	      Utils.writeFile(parentDir.getAbsolutePath(), FILE_NAME, xmlBuffer.toXML());93	    }94	  }95	  private File referenceSuite(XMLStringBuffer xmlBuffer, ISuite suite) {96	    String relativePath = suite.getName() + File.separatorChar + FILE_NAME;97	    File suiteFile = new File(config.getOutputDirectory(), relativePath);98	    Properties attrs = new Properties();99	    attrs.setProperty(XMLReporterConfig.ATTR_URL, relativePath);100	    xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_SUITE, attrs);101	    return suiteFile;102	  }103	  private void writeSuiteToBuffer(XMLStringBuffer xmlBuffer, ISuite suite) {104	    xmlBuffer.push(XMLReporterConfig.TAG_SUITE, getSuiteAttributes(suite));105	    writeSuiteGroups(xmlBuffer, suite);106	    Map<String, ISuiteResult> results = suite.getResults();107	    XMLSuiteResultWriterDRC suiteResultWriter = new XMLSuiteResultWriterDRC(config, true, false, true);108	    for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {109	    	110	    	result.getValue();111	    	//Added exclude logic for failed testCase112	    	//result.getValue().113	      114	    	suiteResultWriter.writeSuiteResult(xmlBuffer, result.getValue());115	    }116	    xmlBuffer.pop();117	  }118	  private void writeSuiteGroups(XMLStringBuffer xmlBuffer, ISuite suite) {119	    xmlBuffer.push(XMLReporterConfig.TAG_GROUPS);120	    Map<String, Collection<ITestNGMethod>> methodsByGroups = suite.getMethodsByGroups();121	    for (Map.Entry<String, Collection<ITestNGMethod>> entry : methodsByGroups.entrySet()) {122	      Properties groupAttrs = new Properties();123	      groupAttrs.setProperty(XMLReporterConfig.ATTR_NAME, entry.getKey());124	      xmlBuffer.push(XMLReporterConfig.TAG_GROUP, groupAttrs);125	      Set<ITestNGMethod> groupMethods = getUniqueMethodSet(entry.getValue());126	      for (ITestNGMethod groupMethod : groupMethods) {127	        Properties methodAttrs = new Properties();128	        methodAttrs.setProperty(XMLReporterConfig.ATTR_NAME, groupMethod.getMethodName());129	        methodAttrs.setProperty(XMLReporterConfig.ATTR_METHOD_SIG, groupMethod.toString());130	        methodAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, groupMethod.getRealClass().getName());131	        xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_METHOD, methodAttrs);132	      }133	      xmlBuffer.pop();134	    }135	    xmlBuffer.pop();136	  }137	  private Properties getSuiteAttributes(ISuite suite) {138	    Properties props = new Properties();139	    props.setProperty(XMLReporterConfig.ATTR_NAME, suite.getName());140	    // Calculate the duration141	    Map<String, ISuiteResult> results = suite.getResults();142	    Date minStartDate = new Date();143	    Date maxEndDate = null;144	    // TODO: We could probably optimize this in order not to traverse this twice145	    for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {146	      ITestContext testContext = result.getValue().getTestContext();147	      Date startDate = testContext.getStartDate();148	      Date endDate = testContext.getEndDate();149	      if (minStartDate.after(startDate)) {150	        minStartDate = startDate;151	      }152	      if (maxEndDate == null || maxEndDate.before(endDate)) {153	        maxEndDate = endDate != null ? endDate : startDate;154	      }155	    }156	    // The suite could be completely empty157	    if (maxEndDate == null) {158	      maxEndDate = minStartDate;159	    }160	    addDurationAttributes(config, props, minStartDate, maxEndDate);161	    return props;162	  }163	  /**164	   * Add started-at, finished-at and duration-ms attributes to the <suite> tag165	   */166	  public static void addDurationAttributes(XMLReporterConfig config, Properties attributes,167	      Date minStartDate, Date maxEndDate) {168	    SimpleDateFormat format = new SimpleDateFormat(XMLReporterConfig.getTimestampFormat());169	    TimeZone utc = TimeZone.getTimeZone("UTC");170	    format.setTimeZone(utc);171	    String startTime = format.format(minStartDate);172	    String endTime = format.format(maxEndDate);173	    long duration = maxEndDate.getTime() - minStartDate.getTime();174	    attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime);175	    attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime);176	    attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, Long.toString(duration));177	  }178	  private Set<ITestNGMethod> getUniqueMethodSet(Collection<ITestNGMethod> methods) {179	    Set<ITestNGMethod> result = new LinkedHashSet<ITestNGMethod>();180	    for (ITestNGMethod method : methods) {181	      result.add(method);182	    }183	    return result;184	  }185	  // TODO: This is not the smartest way to implement the config186	  public int getFileFragmentationLevel() {187	    return config.getFileFragmentationLevel();188	  }189	  public void setFileFragmentationLevel(int fileFragmentationLevel) {190	    config.setFileFragmentationLevel(fileFragmentationLevel);191	  }192	  public int getStackTraceOutputMethod() {193	    return config.getStackTraceOutputMethod();194	  }195	  public void setStackTraceOutputMethod(int stackTraceOutputMethod) {196	    config.setStackTraceOutputMethod(stackTraceOutputMethod);197	  }198	  public String getOutputDirectory() {199	    return config.getOutputDirectory();200	  }201	  public void setOutputDirectory(String outputDirectory) {202	    config.setOutputDirectory(outputDirectory);203	  }204	  public boolean isGenerateGroupsAttribute() {205	    return config.isGenerateGroupsAttribute();206	  }207	  public void setGenerateGroupsAttribute(boolean generateGroupsAttribute) {208	    config.setGenerateGroupsAttribute(generateGroupsAttribute);209	  }210	  public boolean isSplitClassAndPackageNames() {211	    return config.isSplitClassAndPackageNames();212	  }213	  public void setSplitClassAndPackageNames(boolean splitClassAndPackageNames) {214	    config.setSplitClassAndPackageNames(splitClassAndPackageNames);215	  }216	  public String getTimestampFormat() {...Source:GeneratePassedReports.java  
...32  @Override33  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,34      String outputDirectory) {35    if (Utils.isStringEmpty(config.getOutputDirectory())) {36      config.setOutputDirectory(outputDirectory);37    }38    // Calculate passed/failed/skipped39    int passed = 0;40    int failed = 0;41    int skipped = 0;42    for (ISuite s : suites) {43      for (ISuiteResult sr : s.getResults().values()) {44        ITestContext testContext = sr.getTestContext();45        passed += testContext.getPassedTests().size();46        failed += testContext.getFailedTests().size();47        skipped += testContext.getSkippedTests().size();48      }49    }50    rootBuffer = new XMLStringBuffer();51    Properties p = new Properties();52    p.put("passed", passed);53    p.put("failed", failed);54    p.put("skipped", skipped);55    p.put("total", passed + failed + skipped);56    rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS, p);57    writeReporterOutput(rootBuffer);58    for (int i = 0; i < suites.size(); i++) {59      writeSuite(suites.get(i).getXmlSuite(), suites.get(i));60    }61    rootBuffer.pop();62    Utils.writeUtf8File(config.getOutputDirectory(), FILE_NAME, rootBuffer.toXML());63  }64  private void writeReporterOutput(XMLStringBuffer xmlBuffer) {65    // TODO: Cosmin - maybe a <line> element isn't indicated for each line66    xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT);67    List<String> output = Reporter.getOutput();68    for (String line : output) {69      if (line != null) {70        xmlBuffer.push(XMLReporterConfig.TAG_LINE);71        xmlBuffer.addCDATA(line.replace("&", ""));72        xmlBuffer.pop();73      }74    }75    xmlBuffer.pop();76  }77  private void writeSuite(XmlSuite xmlSuite, ISuite suite) {78    switch (config.getFileFragmentationLevel()) {79    case XMLReporterConfig.FF_LEVEL_NONE:80      writeSuiteToBuffer(rootBuffer, suite);81      break;82    case XMLReporterConfig.FF_LEVEL_SUITE:83    case XMLReporterConfig.FF_LEVEL_SUITE_RESULT:84      File suiteFile = referenceSuite(rootBuffer, suite);85      writeSuiteToFile(suiteFile, suite);86    }87  }88  private void writeSuiteToFile(File suiteFile, ISuite suite) {89    XMLStringBuffer xmlBuffer = new XMLStringBuffer();90    writeSuiteToBuffer(xmlBuffer, suite);91    File parentDir = suiteFile.getParentFile();92    if (parentDir.exists() || suiteFile.getParentFile().mkdirs()) {93      Utils.writeFile(parentDir.getAbsolutePath(), FILE_NAME, xmlBuffer.toXML());94    }95  }96  private File referenceSuite(XMLStringBuffer xmlBuffer, ISuite suite) {97    String relativePath = suite.getName() + File.separatorChar + FILE_NAME;98    File suiteFile = new File(config.getOutputDirectory(), relativePath);99    Properties attrs = new Properties();100    attrs.setProperty(XMLReporterConfig.ATTR_URL, relativePath);101    xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_SUITE, attrs);102    return suiteFile;103  }104  private void writeSuiteToBuffer(XMLStringBuffer xmlBuffer, ISuite suite) {105    xmlBuffer.push(XMLReporterConfig.TAG_SUITE, getSuiteAttributes(suite));106    writeSuiteGroups(xmlBuffer, suite);107    Map<String, ISuiteResult> results = suite.getResults();108    XMLSuiteResultWriter suiteResultWriter = new XMLSuiteResultWriter(config);109    for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {110      suiteResultWriter.writeSuiteResult(xmlBuffer, result.getValue());111    }112    xmlBuffer.pop();113  }114  private void writeSuiteGroups(XMLStringBuffer xmlBuffer, ISuite suite) {115    xmlBuffer.push(XMLReporterConfig.TAG_GROUPS);116    Map<String, Collection<ITestNGMethod>> methodsByGroups = suite.getMethodsByGroups();117    for (Map.Entry<String, Collection<ITestNGMethod>> entry : methodsByGroups.entrySet()) {118      Properties groupAttrs = new Properties();119      groupAttrs.setProperty(XMLReporterConfig.ATTR_NAME, entry.getKey());120      xmlBuffer.push(XMLReporterConfig.TAG_GROUP, groupAttrs);121      Set<ITestNGMethod> groupMethods = getUniqueMethodSet(entry.getValue());122      for (ITestNGMethod groupMethod : groupMethods) {123        Properties methodAttrs = new Properties();124        methodAttrs.setProperty(XMLReporterConfig.ATTR_NAME, groupMethod.getMethodName());125        methodAttrs.setProperty(XMLReporterConfig.ATTR_METHOD_SIG, groupMethod.toString());126        methodAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, groupMethod.getRealClass().getName());127        xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_METHOD, methodAttrs);128      }129      xmlBuffer.pop();130    }131    xmlBuffer.pop();132  }133  private Properties getSuiteAttributes(ISuite suite) {134    Properties props = new Properties();135    props.setProperty(XMLReporterConfig.ATTR_NAME, suite.getName());136    // Calculate the duration137    Map<String, ISuiteResult> results = suite.getResults();138    Date minStartDate = new Date();139    Date maxEndDate = null;140    // TODO: We could probably optimize this in order not to traverse this twice141    for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {142      ITestContext testContext = result.getValue().getTestContext();143      Date startDate = testContext.getStartDate();144      Date endDate = testContext.getEndDate();145      if (minStartDate.after(startDate)) {146        minStartDate = startDate;147      }148      if (maxEndDate == null || maxEndDate.before(endDate)) {149        maxEndDate = endDate != null ? endDate : startDate;150      }151    }152    // The suite could be completely empty153    if (maxEndDate == null) {154      maxEndDate = minStartDate;155    }156    addDurationAttributes(config, props, minStartDate, maxEndDate);157    return props;158  }159  /**160   * Add started-at, finished-at and duration-ms attributes to the <suite> tag161   */162  public static void addDurationAttributes(XMLReporterConfig config, Properties attributes,163      Date minStartDate, Date maxEndDate) {164    SimpleDateFormat format = new SimpleDateFormat(XMLReporterConfig.getTimestampFormat());165    TimeZone utc = TimeZone.getTimeZone("UTC");166    format.setTimeZone(utc);167    String startTime = format.format(minStartDate);168    String endTime = format.format(maxEndDate);169    long duration = maxEndDate.getTime() - minStartDate.getTime();170    attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime);171    attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime);172    attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, Long.toString(duration));173  }174  private Set<ITestNGMethod> getUniqueMethodSet(Collection<ITestNGMethod> methods) {175    Set<ITestNGMethod> result = new LinkedHashSet<ITestNGMethod>();176    for (ITestNGMethod method : methods) {177      result.add(method);178    }179    return result;180  }181  // TODO: This is not the smartest way to implement the config182  public int getFileFragmentationLevel() {183    return config.getFileFragmentationLevel();184  }185  public void setFileFragmentationLevel(int fileFragmentationLevel) {186    config.setFileFragmentationLevel(fileFragmentationLevel);187  }188  public int getStackTraceOutputMethod() {189    return config.getStackTraceOutputMethod();190  }191  public void setStackTraceOutputMethod(int stackTraceOutputMethod) {192    config.setStackTraceOutputMethod(stackTraceOutputMethod);193  }194  public String getOutputDirectory() {195    return config.getOutputDirectory();196  }197  public void setOutputDirectory(String outputDirectory) {198    config.setOutputDirectory(outputDirectory);199  }200  public boolean isGenerateGroupsAttribute() {201    return config.isGenerateGroupsAttribute();202  }203  public void setGenerateGroupsAttribute(boolean generateGroupsAttribute) {204    config.setGenerateGroupsAttribute(generateGroupsAttribute);205  }206  public boolean isSplitClassAndPackageNames() {207    return config.isSplitClassAndPackageNames();208  }209  public void setSplitClassAndPackageNames(boolean splitClassAndPackageNames) {210    config.setSplitClassAndPackageNames(splitClassAndPackageNames);211  }212  @SuppressWarnings("static-access")...Source:CustomXMLReporter.java  
...35	@Override36	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,37			String outputDirectory) {38		if (Utils.isStringEmpty(config.getOutputDirectory())) {39			config.setOutputDirectory(outputDirectory);40		}41		// Calculate passed/failed/skipped42		int passed = 0;43		int failed = 0;44		int skipped = 0;45		for (ISuite s : suites) {46			for (ISuiteResult sr : s.getResults().values()) {47				ITestContext testContext = sr.getTestContext();48				passed += testContext.getPassedTests().size();49				failed += testContext.getFailedTests().size();50				skipped += testContext.getSkippedTests().size();51			}52		}53		rootBuffer = new CustomXMLStringBuffer();54		Properties p = new Properties();55		p.put("passed", passed);56		p.put("failed", failed);57		p.put("skipped", skipped);58		p.put("total", passed + failed + skipped);59		rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS, p);60		writeReporterOutput(rootBuffer);61		for (int i = 0; i < suites.size(); i++) {62			writeSuite(suites.get(i).getXmlSuite(), suites.get(i));63		}64		rootBuffer.pop();65		Utils.writeUtf8File(config.getOutputDirectory(), FILE_NAME, rootBuffer,66				null /* no prefix */);67	}68	private void writeReporterOutput(XMLStringBuffer xmlBuffer) {69		// TODO: Cosmin - maybe a <line> element isn't indicated for each line70		xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT);71		List<String> output = Reporter.getOutput();72		for (String line : output) {73			if (line != null) {74				xmlBuffer.push(XMLReporterConfig.TAG_LINE);75				xmlBuffer.addCDATA(line);76				xmlBuffer.pop();77			}78		}79		xmlBuffer.pop();80	}81	private void writeSuite(XmlSuite xmlSuite, ISuite suite) {82		switch (config.getFileFragmentationLevel()) {83		case XMLReporterConfig.FF_LEVEL_NONE:84			writeSuiteToBuffer(rootBuffer, suite);85			break;86		case XMLReporterConfig.FF_LEVEL_SUITE:87		case XMLReporterConfig.FF_LEVEL_SUITE_RESULT:88			File suiteFile = referenceSuite(rootBuffer, suite);89			writeSuiteToFile(suiteFile, suite);90		}91	}92	private void writeSuiteToFile(File suiteFile, ISuite suite) {93		XMLStringBuffer xmlBuffer = new XMLStringBuffer();94		writeSuiteToBuffer(xmlBuffer, suite);95		File parentDir = suiteFile.getParentFile();96		if (parentDir.exists() || suiteFile.getParentFile().mkdirs()) {97			Utils.writeFile(parentDir.getAbsolutePath(), FILE_NAME, xmlBuffer98					.toXML());99		}100	}101	private File referenceSuite(XMLStringBuffer xmlBuffer, ISuite suite) {102		String relativePath = suite.getName() + File.separatorChar + FILE_NAME;103		File suiteFile = new File(config.getOutputDirectory(), relativePath);104		Properties attrs = new Properties();105		attrs.setProperty(XMLReporterConfig.ATTR_URL, relativePath);106		xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_SUITE, attrs);107		return suiteFile;108	}109	private void writeSuiteToBuffer(XMLStringBuffer xmlBuffer, ISuite suite) {110		xmlBuffer.push(XMLReporterConfig.TAG_SUITE, getSuiteAttributes(suite));111		writeSuiteGroups(xmlBuffer, suite);112		Map<String, ISuiteResult> results = suite.getResults();113		XMLSuiteResultWriter suiteResultWriter = new XMLSuiteResultWriter(114				config);115		for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {116			suiteResultWriter.writeSuiteResult(xmlBuffer, result.getValue());117		}118		xmlBuffer.pop();119	}120	private void writeSuiteGroups(XMLStringBuffer xmlBuffer, ISuite suite) {121		xmlBuffer.push(XMLReporterConfig.TAG_GROUPS);122		Map<String, Collection<ITestNGMethod>> methodsByGroups = suite123				.getMethodsByGroups();124		for (Map.Entry<String, Collection<ITestNGMethod>> entry : methodsByGroups125				.entrySet()) {126			Properties groupAttrs = new Properties();127			groupAttrs.setProperty(XMLReporterConfig.ATTR_NAME, entry.getKey());128			xmlBuffer.push(XMLReporterConfig.TAG_GROUP, groupAttrs);129			Set<ITestNGMethod> groupMethods = getUniqueMethodSet(entry130					.getValue());131			for (ITestNGMethod groupMethod : groupMethods) {132				Properties methodAttrs = new Properties();133				methodAttrs.setProperty(XMLReporterConfig.ATTR_NAME,134						groupMethod.getMethodName());135				methodAttrs.setProperty(XMLReporterConfig.ATTR_METHOD_SIG,136						groupMethod.toString());137				methodAttrs.setProperty(XMLReporterConfig.ATTR_CLASS,138						groupMethod.getRealClass().getName());139				xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_METHOD,140						methodAttrs);141			}142			xmlBuffer.pop();143		}144		xmlBuffer.pop();145	}146	private Properties getSuiteAttributes(ISuite suite) {147		Properties props = new Properties();148		props.setProperty(XMLReporterConfig.ATTR_NAME, suite.getName());149		// Calculate the duration150		Map<String, ISuiteResult> results = suite.getResults();151		Date minStartDate = new Date();152		Date maxEndDate = null;153		// TODO: We could probably optimize this in order not to traverse this154		// twice155		for (Map.Entry<String, ISuiteResult> result : results.entrySet()) {156			ITestContext testContext = result.getValue().getTestContext();157			Date startDate = testContext.getStartDate();158			Date endDate = testContext.getEndDate();159			if (minStartDate.after(startDate)) {160				minStartDate = startDate;161			}162			if (maxEndDate == null || maxEndDate.before(endDate)) {163				maxEndDate = endDate != null ? endDate : startDate;164			}165		}166		// The suite could be completely empty167		if (maxEndDate == null) {168			maxEndDate = minStartDate;169		}170		addDurationAttributes(config, props, minStartDate, maxEndDate);171		return props;172	}173	/**174	 * Add started-at, finished-at and duration-ms attributes to the <suite> tag175	 */176	public static void addDurationAttributes(XMLReporterConfig config,177			Properties attributes, Date minStartDate, Date maxEndDate) {178		SimpleDateFormat format = new SimpleDateFormat(XMLReporterConfig179				.getTimestampFormat());180		TimeZone utc = TimeZone.getTimeZone("UTC");181		format.setTimeZone(utc);182		String startTime = format.format(minStartDate);183		String endTime = format.format(maxEndDate);184		long duration = maxEndDate.getTime() - minStartDate.getTime();185		attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime);186		attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime);187		attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, Long188				.toString(duration));189	}190	private Set<ITestNGMethod> getUniqueMethodSet(191			Collection<ITestNGMethod> methods) {192		Set<ITestNGMethod> result = new LinkedHashSet<ITestNGMethod>();193		for (ITestNGMethod method : methods) {194			result.add(method);195		}196		return result;197	}198	// TODO: This is not the smartest way to implement the config199	public int getFileFragmentationLevel() {200		return config.getFileFragmentationLevel();201	}202	public void setFileFragmentationLevel(int fileFragmentationLevel) {203		config.setFileFragmentationLevel(fileFragmentationLevel);204	}205	public int getStackTraceOutputMethod() {206		return 1;207		// return config.getStackTraceOutputMethod();208	}209	public void setStackTraceOutputMethod(int stackTraceOutputMethod) {210		config.setStackTraceOutputMethod(stackTraceOutputMethod);211	}212	public String getOutputDirectory() {213		return config.getOutputDirectory();214	}215	public void setOutputDirectory(String outputDirectory) {216		config.setOutputDirectory(outputDirectory);217	}218	public boolean isGenerateGroupsAttribute() {219		return config.isGenerateGroupsAttribute();220	}221	public void setGenerateGroupsAttribute(boolean generateGroupsAttribute) {222		config.setGenerateGroupsAttribute(generateGroupsAttribute);223	}224	public boolean isSplitClassAndPackageNames() {225		return config.isSplitClassAndPackageNames();226	}227	public void setSplitClassAndPackageNames(boolean splitClassAndPackageNames) {228		config.setSplitClassAndPackageNames(splitClassAndPackageNames);229	}230	public String getTimestampFormat() {...Source:XMLReporter.java  
...29	private XMLReporterConfig config = new XMLReporterConfig();30	private XMLStringBuffer rootBuffer;31	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {32		if (Utils.isStringEmpty(config.getOutputDirectory())) {33			config.setOutputDirectory(outputDirectory);34		}35		rootBuffer = new XMLStringBuffer("");36		rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS);37		writeReporterOutput(rootBuffer);38		for (int i = 0; i < suites.size(); i++) {39			writeSuite(xmlSuites.get(i), suites.get(i));40		}41		rootBuffer.pop();42		// Utils.writeUtf8File(config.getOutputDirectory(),43		// "testng-results-spire.xml", rootBuffer.toXML());44		try {45			Utils.writeUtf8File(ContextManager.getGlobalContext().getOutputDirectory(), "testng-results-spire.xml", rootBuffer.toXML());46		} catch (Throwable e) {47			logger.warn("Ex", e);48		}49	}50	// TODO: This is not the smartest way to implement the config51	public int getFileFragmentationLevel() {52		return config.getFileFragmentationLevel();53	}54	public String getOutputDirectory() {55		return config.getOutputDirectory();56	}57	public int getStackTraceOutputMethod() {58		return config.getStackTraceOutputMethod();59	}60	private Properties getSuiteAttributes(ISuite suite) {61		Properties props = new Properties();62		props.setProperty(XMLReporterConfig.ATTR_NAME, suite.getName());63		return props;64	}65	public String getTimestampFormat() {66		return XMLReporterConfig.getTimestampFormat();67	}68	private Set<ITestNGMethod> getUniqueMethodSet(Collection<ITestNGMethod> methods) {69		Set<ITestNGMethod> result = new LinkedHashSet<ITestNGMethod>();70		for (ITestNGMethod method : methods) {71			result.add(method);72		}73		return result;74	}75	public boolean isGenerateDependsOnGroups() {76		return config.isGenerateDependsOnGroups();77	}78	public boolean isGenerateDependsOnMethods() {79		return config.isGenerateDependsOnMethods();80	}81	public boolean isGenerateGroupsAttribute() {82		return config.isGenerateGroupsAttribute();83	}84	public boolean isSplitClassAndPackageNames() {85		return config.isSplitClassAndPackageNames();86	}87	private File referenceSuite(XMLStringBuffer xmlBuffer, ISuite suite) {88		String relativePath = suite.getName() + File.separatorChar + "testng-results.xml";89		File suiteFile = new File(config.getOutputDirectory(), relativePath);90		Properties attrs = new Properties();91		attrs.setProperty(XMLReporterConfig.ATTR_URL, relativePath);92		xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_SUITE, attrs);93		return suiteFile;94	}95	public void setFileFragmentationLevel(int fileFragmentationLevel) {96		config.setFileFragmentationLevel(fileFragmentationLevel);97	}98	public void setGenerateDependsOnGroups(boolean generateDependsOnGroups) {99		config.setGenerateDependsOnGroups(generateDependsOnGroups);100	}101	public void setGenerateDependsOnMethods(boolean generateDependsOnMethods) {102		config.setGenerateDependsOnMethods(generateDependsOnMethods);103	}104	public void setGenerateGroupsAttribute(boolean generateGroupsAttribute) {105		config.setGenerateGroupsAttribute(generateGroupsAttribute);106	}107	public void setOutputDirectory(String outputDirectory) {108		config.setOutputDirectory(outputDirectory);109	}110	public void setSplitClassAndPackageNames(boolean splitClassAndPackageNames) {111		config.setSplitClassAndPackageNames(splitClassAndPackageNames);112	}113	public void setStackTraceOutputMethod(int stackTraceOutputMethod) {114		config.setStackTraceOutputMethod(stackTraceOutputMethod);115	}116	public void setTimestampFormat(String timestampFormat) {117		config.setTimestampFormat(timestampFormat);118	}119	private void writePoolBuildInformation(ISuite suite, XMLStringBuffer xmlBuffer) {120		Properties prop = new Properties();121		prop.put("user", System.getProperty("user.name"));122		try {...Source:EMReporter.java  
...31  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {32	  // if output directory not set, then set it.33	  System.out.println("Sundeep the directory s " + config.getOutputDirectory() + outputDirectory);34    if (Utils.isStringEmpty(config.getOutputDirectory())) {35      config.setOutputDirectory(outputDirectory);36    }37    rootBuffer = new XMLStringBuffer("");38    rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS);39     writeReporterOutput(rootBuffer);40    for (int i = 0; i < suites.size(); i++) {41      writeSuite(suites.get(i).getXmlSuite(), suites.get(i));42    }43    44    rootBuffer.pop();45    Utils.writeUtf8File(config.getOutputDirectory(), "abeer-results.xml", rootBuffer.toXML());46  }47  	private void writeReporterOutput(XMLStringBuffer xmlBuffer) {48  		//TODO: Cosmin - maybe a <line> element isn't indicated for each line49  		xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT);...setOutputDirectory
Using AI Code Generation
1import org.testng.ITestResult;2import org.testng.TestListenerAdapter;3import org.testng.reporters.XMLReporterConfig;4public class XmlReportListener extends TestListenerAdapter {5    public void onTestFailure(ITestResult tr) {6        super.onTestFailure(tr);7        System.out.println("Test Failed");8        XMLReporterConfig xmlReporterConfig = new XMLReporterConfig();9        xmlReporterConfig.setOutputDirectory("/Users/username/Desktop/Reports");10    }11}12Note: In the above example, the XMLReporterConfig class is imported from the org.testng.reporters package. This class is not available in the latest version of TestNG. So, you need to add the dependency for the TestNG versionsetOutputDirectory
Using AI Code Generation
1import org.testng.reporters.XMLReporterConfig;2import org.testng.reporters.XMLReporter;3XMLReporterConfig config = new XMLReporterConfig();4config.setOutputDirectory("C:\\test-output");5XMLReporter reporter = new XMLReporter(config);6import org.testng.reporters.SuiteHTMLReporter;7SuiteHTMLReporter reporter = new SuiteHTMLReporter();8reporter.setOutputDirectory("C:\\test-output");9import org.testng.reporters.JUnitReportReporter;10JUnitReportReporter reporter = new JUnitReportReporter();11reporter.setOutputDirectory("C:\\test-output");12import org.testng.reporters.EmailableReporter;13EmailableReporter reporter = new EmailableReporter();14reporter.setOutputDirectory("C:\\test-output");15import org.testng.reporters.JUnitXMLReporter;16JUnitXMLReporter reporter = new JUnitXMLReporter();17reporter.setOutputDirectory("C:\\test-output");18import org.testng.reporters.FailedReporter;19FailedReporter reporter = new FailedReporter();20reporter.setOutputDirectory("C:\\test-output");21import org.testng.reporters.JUnitReportReporter;22JUnitReportReporter reporter = new JUnitReportReporter();23reporter.setOutputDirectory("C:\\test-output");24import org.testng.reporters.SuiteHTMLReporter;25SuiteHTMLReporter reporter = new SuiteHTMLReporter();26reporter.setOutputDirectory("C:\\test-output");27import org.testng.reporters.XMLReporter;28XMLReporter reporter = new XMLReporter();29reporter.setOutputDirectory("C:\\test-output");30import org.testng.reporters.EmailableReporter;31EmailableReporter reporter = new EmailableReporter();32reporter.setOutputDirectory("C:\\test-output");33importsetOutputDirectory
Using AI Code Generation
1import org.testng.reporters.XMLReporterConfig;2public class TestNGListener implements ITestListener {3    public void onTestStart(ITestResult result) {4    }5    public void onTestSuccess(ITestResult result) {6    }7    public void onTestFailure(ITestResult result) {8    }9    public void onTestSkipped(ITestResult result) {10    }11    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {12    }13    public void onStart(ITestContext context) {14        XMLReporterConfig.getInstance().setOutputDirectory("test-output");15    }16    public void onFinish(ITestContext context) {17    }18}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!!
