@BeforeSuite:在此套件中的所有测试都运行之前,将运行带注释的方法。
@AfterSuite:在此套件中的所有测试都运行之后,将会运行带注释的方法。
@BeforeTest:在任何属于标签内的类的测试方法运行之前,将会运行带注释的方法。
@AfterTest:在所有属于标记内的类的测试方法都运行之后,将会运行带注释的方法。
@BeforeGroups:在第一个属于这些组中的任何一个的测试方法被调用之前运行。
@AfterGroups:在最后一个属于这些组中的最后一个测试方法被调用后马上运行。
@BeforeClass:注释的方法将在当前类中的第一个测试方法被调用之前运行。
@AfterClass:在当前类的所有测试方法都运行后,将会运行带注释的方法。
@BeforeMethod:注解的方法将在每个测试方法之前运行。
@AfterMethod:注解的方法将在每个测试方法之后运行。
参数:
alwaysRun:对于前置方法(beforeSuite,beforeTest,beforeTestClass和beforeTestMethod,但不是beforeGroups),如果设置为true,则将运行此配置方法,而不管它属于哪个组。
对于after方法(afterSuite,afterClass,…):如果设置为true,即使先前调用的一个或多个方法失败或被跳过,也将运行此配置方法。
dependsOnGroups 依赖某个组
dependsOnMethods 依赖某个方法列表.
enabled 是否启用该方法
groups 测试类或方法属于某个组
inheritGroups If true, this method will belong to groups specified in the @Test annotation at the class level.@BeforeSuite(alwaysRun="true") @AfterSuite(alwaysRun="true")
TestNG类的超类中的注释行为
当放置在TestNG类的超类上时,上面的注释也将被承认(继承)。
这对于例如集中在一个公共超类中的多个测试类的测试设置是有用的。
在这种情况下,TestNG保证以继承顺序执行“@Before”方法
(首先是最高超类,然后是继承链),然后是相反顺序的“@After”方法(继承链)
@Parameters:给测试方法参数赋值。
@Parameters(value = {"param1", "param2"}) @Test public void test(String arg1, String arg2) { }
@Factory用于一个工厂模式的测试方法,
一般我们会在标有@Factory注解的方法中对测试类进行调用,这时TestNg会自动调用测试类中带有@Test注解的方法
/*创建一个工厂类,把同一组参数传递给多个测试方法*/ public class TestFactoryClass { @Factory(dataProvider = "datasource") public Object[] TestFactory(String str1,String str2){ Object[] objects=new Object[2]; objects[0]=new LoginPage(str1,str2); objects[1]=new HomePage(str1,str2); return objects; } }
public class HomePage { private String str1; private String str2; public HomePage(String str1,String str2){ this.str1=str1; this.str2=str2; } @Test public void testHomePage() { System.out.println(str1 + " - " + str2 + " is testing Home page"); } }
public class LoginPage{ private String str1; private String str2; public LoginPage(String str1,String str2){ this.str1=str1; this.str2=str2; } @Test public void testLoginPage() { System.out.println(str1 + " - " + str2 + " is testing Login page"); } }
<suite name="TestFactoryClass" parallel="false"> <test name="Demo_Test"> <classes> <class name="TestFactoryClass" /> </classes> </test> </suite>
@Test 参数:
@Test(param1 = ..., param2 = ...)
alwaysRun:同上
dataProvider:声明data provider@DataProvider(name="datasource") public Object[][] datasource() { return new Object[][]{{"value1-1", "value2-1"}, {"value1-2", "value2-2"}, {"value1-3", "value2-3"}}; } @Test(dataProvider="datasource") public void test(String arg1, String arg2) { }
dataProviderClass:声明提供data provider的类,如果没有定义这个参数,则默认在当前test的类和其基类寻找,如果定义了这个参数,data provider方法应该为静态。
dependsOnGroups
dependsOnMethods
description:方法的描述。
enabled:是否开启方法。
expectedExceptions:希望该测试抛出的异常列表的类,如果没有异常或者抛出异常不在列表里,则报错。@Test(expectedExceptions = ExceptionInInitializerError.class) public void testcase3(){ throw new ExceptionInInitializerError(); }
invocationCount:这个方法应该被调用的次数。
public class TestAnnotationPropertiesTest { @Test(priority = 1, invocationCount = 3) public void test1() { System.out.println("invoke test1"); } @Test(priority = 2, invocationCount = 2) public void test2() { System.out.println("invoke test2"); } } 运行结果: invoke test1 invoke test1 invoke test1 invoke test2 invoke test2
invocationTimeOut: 每一次调用的超时时间,如果invocationCount没有指定,该参数会被忽略。应用场景可以为:测试获取数据库连接,超时就认定为失败。单位是毫秒。
priority:测试方法的优先级,priority的值越低,优先级越高。
successPercentage:希望该测试方法的成功百分比。
singleThreaded:如果设置为true,即使当前正在使用parallel =“methods”运行测试,此测试类中的所有方法也保证在同一个线程中运行。该属性只能在类级别使用,如果在方法级别使用,则该属性将被忽略。注意:此属性过去被称为 sequential (现在已被弃用)。
timeOut:该测试方法应该用的最大毫秒数。
threadPoolSize:此方法的线程池的大小。该方法将由invocationCount指定的多个线程调用。
注意:如果未指定invocationCount,则忽略此属性。
依赖
使用@Test的属性dependsOnMethods或dependsOnGroups。
**硬依赖:**所依赖的测试失败后会skip当前测试。
**软依赖:**依赖的测试失败后会继续按顺序运行测试。使用 alwaysRun=true 来使用软依赖。
命令行运行testng
java org.testng.TestNG testng1.xml
可以传递参数, -d 为指定report输出的目录
java org.testng.TestNG -d output testng1.xml
传递java的命令行的参数
java -Dtestng.test.classpath="c:/build;c:/java/classes;" org.testng.TestNG testng.xml
Listener
在testng.xml定义监听器
<Suite> <listeners> <listener class-name="com.is.xxxListener"/> <listener class-name="com.is.MyMethodInterceptor"/> </listeners> </Suite>
在代码中注释
@Listeners({com.is.xxxListener.class,com.is.MyMethodInterceptor.class}) public class Test{}
IAnnotationTransformer
修改源代码中@Test的注释
public class TestListener implements IAnnotationTransformer { @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.getAlwaysRun(); testClass.getClass(); if ("invoke".equals(testMethod.getName())) { annotation.setInvocationCount(5); } } }
TestNG testng=new TestNG(); testng.setAnnotationTransformer(new TestListener();)
IAnnotationTransformer2
修改源代码中@Factory,@DataProvider, @Configuration的注释
public class TestListener implements IAnnotationTransformer2 { @Override public void transform(IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.getAfterSuite(); } @Override public void transform(IDataProviderAnnotation annotation, Method method) { annotation.isParallel(); } @Override public void transform(IFactoryAnnotation annotation, Method method) { annotation.getIndices(); } @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.getAlwaysRun(); testClass.getClass(); testMethod.getName(); } }
IHookable
在测试方法前后加入切入点,类似AOP中的 Around Advice 的功能,从而在运行前后实现特定功能。例如,用户可以在当前测试方法运行前加入特定的验证逻辑以决定测试方法是否运行或者跳过,甚至覆盖测试方法的逻辑。
public class TestListener implements IHookable { @Override public void run(IHookCallBack callBack, ITestResult testResult) { } }
IInvokedMethodListener
提供了类似与面向方面编程(AOP)中的 Before Advice 和 After Advice 的功能。它允许用户在当前测试方法被执行前和执行后注入特定的逻辑,比如,可以加入日志方法。
public class TestListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { method.getTestResult(); testResult.isSuccess() } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { } }
IMethodInterceptor
TestNG运行测试方法有两种,一种是顺序的,一种是随机的,此方法可以控制随机运行的测试方法。
public class TestListener implements IMethodInterceptor { @Override public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) { methods.clear(); context.getEndDate(); return null; } }
IReporter
TestNG 提供了默认的测试报表。但如果用户希望有不同格式的测试报表,就需要使用 IReporter 监听器。
public class TestListener implements IReporter { @Override public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) { xmlSuites.clear(); suites.clear(); outputDirectory=""; } }
ITestListener
在用例失败、成功、跳过 之后定义后续行为。
public class TestListener implements ITestListener { @Override public void onTestStart(ITestResult result) { } @Override public void onTestSuccess(ITestResult result) { } @Override public void onTestFailure(ITestResult result) { } @Override public void onTestSkipped(ITestResult result) { } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { } @Override public void onStart(ITestContext context) { } @Override public void onFinish(ITestContext context) { } }
ISuiteListener
类似于IInvokeMethodListener,只是针对suite.
public class TestListener implements ISuiteListener { @Override public void onStart(ISuite suite) { } @Override public void onFinish(ISuite suite) { } }
TestListenerAdapter
实现该接口创建自定义日志类。调用了ITestListener中的方法。
XML report
可以生成XML格式的报告
<testng-results> <suite name="Suite1"> <groups> <group name="group1"> <method signature="com.test.TestOne.test2()" name="test2" class="com.test.TestOne"/> <method signature="com.test.TestOne.test1()" name="test1" class="com.test.TestOne"/> </group> <group name="group2"> <method signature="com.test.TestOne.test2()" name="test2" class="com.test.TestOne"/> </group> </groups> <test name="test1"> <class name="com.test.TestOne"> <test-method status="FAIL" signature="test1()" name="test1" duration-ms="0" started-at="2007-05-28T12:14:37Z" description="someDescription2" finished-at="2007-05-28T12:14:37Z"> <exception class="java.lang.AssertionError"> <short-stacktrace> <![CDATA[ java.lang.AssertionError ... Removed 22 stack frames ]]> </short-stacktrace> </exception> </test-method> <test-method status="PASS" signature="test2()" name="test2" duration-ms="0" started-at="2007-05-28T12:14:37Z" description="someDescription1" finished-at="2007-05-28T12:14:37Z"> </test-method> <test-method status="PASS" signature="setUp()" name="setUp" is-config="true" duration-ms="15" started-at="2007-05-28T12:14:37Z" finished-at="2007-05-28T12:14:37Z"> </test-method> </class> </test> </suite> </testng-results>
outputDirectory:报告输出的路径。
timestampFormat: 定义报告生成日期的格式。默认 yyyy-MM-dd’T’HH:mm:ss’Z’
fileFragmentationLevel:XML文件生成的方式:1,2,3,默认1:
1 - 所有结果在一个文件里。
2 - 每个suite生成一个xml文件,最后link到一个主要文件。
3 - same as 2 plus separate files for test-cases that are referenced from the suite files.
splitClassAndPackageNames:
This boolean specifies the way that class names are generated for the <class> element. For example, you will get <class class="com.test.MyTest"> for false and <class class="MyTest" package="com.test"> for true. 默认false。
generateGroupsAttribute:
A boolean indicating if a groups attribute should be generated for the <test-method> element. This feature aims at providing a straight-forward method of retrieving the groups that include a test method without having to surf through the <group> elements. 默认false
generateTestResultAttributes:
A boolean indicating if an <attributes> tag should be generated for each <test-method> element, containing the test result attributes (See ITestResult.setAttribute() about setting test result attributes). Each attribute toString() representation will be written in a <attribute name="[attribute name]"> tag. 默认false
stackTraceOutputMethod:
Specifies the type of stack trace that is to be generated for exceptions and has the following values,默认为2:
- 0 - no stacktrace (just Exception class and message).
- 1 - a short version of the stack trace keeping just a few lines from the top
- 2 - the complete stacktrace with all the inner exceptions
- 3 - both short and long stacktrace
generateDependsOnMethods:
Use this attribute to enable/disable the generation of a depends-on-methods attribute for the <test-method> element. 默认true
generateDependsOnGroups:
Enable/disable the generation of a depends-on-groups attribute for the <test-method> element.
preserve-order:
用来控制<test>里面所有<classes>的执行顺序。<test>中默认的preserve-order为true,表示<test>下所有<classes>按照顺序执行
verbose:
命令行信息打印等级,不会影响测试报告输出内容;可选值(1|2|3|4|5)
**setEscapeHtml(false):防止转义