1. TestNG API
本篇将讨论如何使用TestNG API来创建自己的TestNG对象。TestNG的API基本由接口组成,这样做是为了容易模拟TestNG返回的对象。
1.1 org.testng.TestNG、ITestResult、ITestListener、ITestNGMethod
TestNG类是TestNG的的主入口,它让我们指定测试类,指定包含的分组或排除的分组,指定要执行的XML文件等。
public static void mian(String[] args){ TestNG tng = new TestNG(); tng.setTestClasses(new Class[]{ MyTest.class}); TestListenerAdapter listener = new TestListenerAdapter(); tng.addListener(listener); tng.run(); log("PASSED:" + listener.getPassedTests().size()); } |
这里TestListenerAdapter类提供了ITestListener接口的一个简单实现。这里使用TestListenerAdapter的另一项功能:记录所有通过的测试案例数量。
通过TestListenerAdapter可以方便的获取结果的程序清单,如果需要为这个类添加功能,又保留测试结果程序清单,则可以调用被覆盖方法的super()方法,如下所示:
public class MyTestListener extends TestListenerAdapter{ public void onTestSuccess(ITestResult result){ super.onTestSuccess(result); //do you own processing } } |
TestListenerAdapter 保存了测试结果:
public List<ITestResult> getPassedTests() public List<ITestResult> getFailedTests() public List<ITestResult> getSkippedTests() |
ITestResult 接口能让我们获取某个测试状态、测试方法、参数,以及开始时间和结束时间:
public void onTestSuccess(ITestResult iTestResult) { long time = (iTestResult.getEndMillis() - iTestResult.getStartMillis()); log("Success, method:" + iTestResult.getMethod() +" #parameters:"+iTestResult.getParameters().length + " time:" + time); } |
ITestResult# getResult 返回一个ITestNGMethod,这个是TestNG对测试方法的一个视图。从这个对象我们可以获得TestNG对象当前调用的原始java.lang.reflact.Method, 并获得其他信息,如:
分组/方法信息(这个方法所属的分组,它依赖的分组和方法)。
调用的次数,线程池的大小以及超时设置。
这个方法是否是一个配置方法(@Before/@After), 它是哪一种配置方法:
ITestNGMethod method = iTestResult.getMethod(); log(" Method:"+method.getMethodName() +" invocationCount:" +method.getInvocationCount() +" #groups:"+method.getGroups().length +" timeOut:"+method.getTimeOut()); |
1.2 XML API
TestNG提供了一个简单的接口,让我们访问自己的testng.xml, 甚至可以从头创建它。与XML API相关的这些类在org.testng.xml中,每个XML标签都有一个对应的类:
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。