我目前正在使用工厂运行一组测试。如何记录每次测试所花费的时间,然后报告类(class)每个实例中每次测试所花费的平均时间。例如:
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 秒?
最佳答案
您可以使用@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
关于java - 使用 TestNG Factory 获取测试方法实例的平均运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39027460/