使用 TestNG 工厂获取测试方法实例的平均运行时间

Getting average runtime of instances of test method using a TestNG Factory

我目前正在 运行 一组使用工厂的测试。我如何记录每个测试花费的时间,然后报告 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