gpt4 book ai didi

java - 如何使用 runlistener 创建 JUNIT 报告?

转载 作者:行者123 更新时间:2023-12-01 18:25:48 24 4
gpt4 key购买 nike

我一直在使用 JUNIT 进行测试。我能够运行我的测试用例,但问题是如何使用 runlistener 以编程方式创建 JUNIT 报告(不使用 ANT 或 MAVEN)。我有点卡住了,希望得到任何指导。

监听器实现:-

JUnitCore junit = new JUnitCore();

junit.addListener(new MyJunitListener());

junit.run(AllEJBJunitTests.class);

我如何继续创建报告?

最佳答案

您可以使用 StringBuffer 生成 HTML 报告。

String filePath = "File path where you want to keep your report";
String reportFileName = "myReport.htm";

JUnitCore junit = new JUnitCore();
junit.addListener(new MyJunitListener());
Result result = junit.run(AllEJBJunitTests.class);
StringBuffer myContent = getResultContent(result, size);//Size represents number of AllEJBJunitTests class, suppose if you have 5 EJB classes then size is 5.
writeReportFile(filePath + "/" + reportFileName, myContent);

//此方法将为您提供 HTML 内容。

private StringBuffer getResultContent(Result result, int numberOfTestFiles)
{
int numberOfTest = result.getRunCount();
int numberOfTestFail = result.getFailureCount();
int numberOfTestIgnore = result.getIgnoreCount();
int numberOfTestSuccess = numberOfTest - numberOfTestFail - numberOfTestIgnore;
int successPercent = (numberOfTest != 0) ? numberOfTestSuccess * 100 / numberOfTest : 0;
double time = result.getRunTime();
StringBuffer myContent = new StringBuffer("<h1>Junitee Test Report</h1><h2>Result</h2><table border=\"1\"><tr><th>Test Files</th><th>Tests</th><th>Success</th>");
if ((numberOfTestFail > 0) || (numberOfTestIgnore > 0)) {
myContent.append("<th>Failure</th><th>Ignore</th>");
}

myContent.append("<th>Test Time (seconds)</th></tr><tr");
if ((numberOfTestFail > 0) || (numberOfTestIgnore > 0)) {
myContent.append(" style=\"color:red\" ");
}
myContent.append("><td>");
myContent.append(numberOfTestFiles);
myContent.append("</td><td>");
myContent.append(numberOfTest);
myContent.append("</td><td>");
myContent.append(successPercent);
myContent.append("%</td><td>");
if ((numberOfTestFail > 0) || (numberOfTestIgnore > 0)) {
myContent.append(numberOfTestFail);
myContent.append("</td><td>");
myContent.append(numberOfTestIgnore);
myContent.append("</td><td>");
}

myContent.append(Double.valueOf(time / 1000.0D));
myContent.append("</td></tr></table>");
return myContent;
}

//这将在您提到的特定目录中生成报告。

private void writeReportFile(String fileName,StringBuffer reportContent){
FileWriter myFileWriter = null;
try {
myFileWriter = new FileWriter(fileName);
myFileWriter.write(reportContent.toString());
}
catch (IOException e) {

}
finally {
if (myFileWriter!=null) {
try {
myFileWriter.close();
}
catch (IOException e) {

}
}
}
}

干杯!!

关于java - 如何使用 runlistener 创建 JUNIT 报告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26257635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com