2017-08-25 56 views
0

我在测试套件中有一堆测试。TestNG:如何验证通用函数中的测试结果

@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() 
} 

要利用这些断言在验证()时,直截了当的方式我能想到的是添加验证()在每次试验结束。但是有没有更优雅或更简单的方式呢?

我看了一下TestNG的@AfterMethod(和@AfterTest)。如果我添加@AfterMethod来验证(),则会执行verify()中的断言。但是,如果断言通过,它们不会显示在测试报告中。如果断言失败,那些失败标记为配置失败,而不是测试失败。

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

谢谢!

回答

2

你基本上可以让你的测试类实现接口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 
===============================================