我的测试套件中有一堆测试。
@Test
public void test1() {
// test 1
assert...
}
@Test
public void test2() {
// test 2
assert...
}我有另一个名为'verify()‘的方法,它在测试完成后执行一些额外的断言。
void verify() {
// more asserts that are common to test1() and test2()
}要在verify()中使用这些断言,我能想到的最简单的方法是在每个测试的末尾添加verify()。但是,有没有比这更优雅或更简单的方式呢?
我查看了TestNG的@AfterMethod (和@AfterTest)。如果我在verify()中添加@AfterMethod,那么verify()中的断言就会被执行。但是如果断言通过,它们就不会出现在测试报告中。如果断言失败,这些失败将被标记为配置失败,而不是测试失败。
如何确保每次测试运行后始终调用verify(),并仍然报告verify()中断言的结果作为测试结果的一部分?
谢谢!
发布于 2017-08-25 15:41:12
基本上,您可以让测试类实现接口org.testng.IHookable。
当TestNG发现一个类实现了这个接口时,TestNG不会直接调用您的@Test方法,而是从IHookable实现中调用run()方法,在这个实现中,您需要通过调用传递给您的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
===============================================https://stackoverflow.com/questions/45875541
复制相似问题