我目前正在使用Factory运行一组测试。如何记录每个测试所花费的时间,然后报告每个测试的平均时间。例如:
public class TestFactory {
@Factory
public Object[] create() {
return new Object[] {
new TestClass("1"), new TestClass("2")
};
}
}
public class TestClass {
private int x;
public TestClass(int i) {
x = i;
}
@Test(priority=1)
public void test1() {
System.out.println("test 1 : " + x + "!");
}
@Test(priority=2)
public void test2() {
System.out.println("test 2 : " + x + "!");
}
}
这将产生输出:
test 1 : 1! (assume this ran in 1 second)
test 2 : 1! (assume this ran in 2 seconds)
test 1 : 2! (assume this ran in 0.5 seconds)
test 2 : 2! (assume this ran in 1 second)
我知道我可以使用@AfterMethod和ITestResult来计算实例中每个方法的运行时间,并获得test1和test2的运行时。但是,如何计算test1和test2运行的所有实例的平均运行时间,以便我知道test1的平均运行时间为0.75秒,而test2的平均运行时间为1.5秒?
答案 0 :(得分:1)
您可以使用@org.testng.annotations.Listeners
。
public class AverageReport implements ISuiteListener {
@Override
public void onStart(final ISuite iSuite) {
}
@Override
public void onFinish(final ISuite iSuite) {
// group runtimes per method
Map<String, List<Double>> runtimes = new HashMap<>();
for (IInvokedMethod method : iSuite.getAllInvokedMethods()) {
ITestResult result = method.getTestResult();
long runtime = result.getEndMillis() - result.getStartMillis();
String methodName = method.getTestMethod().getMethodName();
runtimes.computeIfAbsent(methodName, (name) -> new ArrayList<>())
.add((double) runtime);
}
// calculate averages and report
averages.forEach((methodName, value) ->
value.stream()
.mapToDouble(a -> a)
.average()
.ifPresent(avg ->
// Put your reporting code here
System.err.println(
methodName + " average runtime is " + avg + "ms"
)
));
}
}
然后您可以在工厂中使用此注释:
@Listeners(AverageReport.class)
public class TestFactory {
@Factory
public Object[] create() {
return new Object[] {
new TestClass(1), new TestClass(2)
};
}
}
在完成所有测试后,您将获得这样的输出
test2 average runtime is 31.0ms
test1 average runtime is 26.5ms