TestNG:如何在常用功能中验证测试结果

时间:2017-08-25 06:26:24

标签: java unit-testing testng

我的测试套件中有很多测试。

bmesh.ops.delete()

我有另一种名为' verify()'在测试完成后会做一些额外的断言。

@Test
public void test1() {
  // test 1
  assert...
}

@Test
public void test2() {
  // test 2
  assert...
}

要在verify()中使用这些断言,我能想到的直接方法是在每次测试结束时添加verify()。但这有更优雅或更简单的方式吗?

我看了TestNG的@AfterMethod(和@AfterTest)。如果我将@AfterMethod添加到verify(),则执行verify()中的断言。但是如果断言通过,它们就不会出现在测试报告中。如果断言失败,则将这些失败标记为配置失败而不是测试失败。

如何确保在每次测试运行后始终调用verify()并仍然在verify()中报告断言结果作为测试结果的一部分?

谢谢!

1 个答案:

答案 0 :(得分:2)

您基本上可以让测试类实现接口org.testng.IHookable

当TestNG发现某个类实现了此接口时,TestNG不会直接调用您的@Test方法,而是从run()实现中调用IHookable方法。期望通过调用传递给你的org.testng.IHookCallBack上的回调来触发测试方法调用。

以下是展示此动作的示例:

import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.Test;

public class MyTestClass implements IHookable {
    @Override
    public void run(IHookCallBack callBack, ITestResult testResult) {
        callBack.runTestMethod(testResult);
        commonTestCode();
    }

    public void commonTestCode() {
        System.err.println("commonTestCode() executed.");

    }

    @Test
    public void testMethod1() {
        System.err.println("testMethod1() executed.");
    }

    @Test
    public void testMethod2() {
        System.err.println("testMethod2() executed.");
    }
}

这是执行的输出:

testMethod1() executed.
commonTestCode() executed.
testMethod2() executed.
commonTestCode() executed.

===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================