TestNG测试框架官网简要翻译

1 - Introduction
TestNG是一个测试框架,旨在简化广泛的测试需求,从单元测试(测试一个类隔离其他类)到集成测试(测试整个系统由几个类、几个包甚至几个外部框架组成,比如应用服务器)。
编写测试通常是三个步骤:
编写测试的业务逻辑,并在代码中插入TestNG注释。
在testng中添加关于您的测试的信息(例如类名、您希望运行的组等等)。
xml文件或在build.xml中。
TestNG运行。
您可以在欢迎页面上找到一个快速示例。
本文件中使用的概念如下:
一个套件由一个XML文件表示。
它可以包含一个或多个测试,并由标记定义。
测试用表示,可以包含一个或多个TestNG类。
TestNG类是一个包含至少一个TestNG注释的Java类。
它由标记并可以包含一个或多个测试方法来表示。
测试方法是在源代码中通过@Test注释的Java方法。
TestNG测试可以通过@BeforeXXX和@AfterXXX注解来配置,它允许在某个点之前和之后执行一些Java逻辑,这些点都是上面列出的项目。
本手册的其余部分将解释以下内容:
所有注释的列表,并附有简要说明。
这将让您了解TestNG提供的各种功能,但是您可能会希望查阅专门针对每个注释的部分来了解细节。
对testng的描述。
xml文件,它的语法和您可以在其中指定的内容。
详细列出了各种特性,以及如何将它们与注释和testng.xml结合使用。

2 - Annotations
@BeforeSuite:在此套件中所有测试运行之前,将运行带注释的方法。
@AfterSuite:在该套件中所有测试运行后,将运行带注释的方法。
@ beshowest:在运行标记内的类的任何测试方法之前,将运行带注释的方法。
@AfterTest:在标记内的所有测试方法都已运行之后,将运行注释方法。
@BeforeGroups:此配置方法将在之前运行的组列表。这个方法保证在第一个测试方法被调用之前运行。
@AfterGroups:此配置方法将在后面运行的组列表。该方法保证在调用属于这些组的最后一个测试方法后不久运行。
@BeforeClass:在调用当前类中的第一个测试方法之前,将运行带注释的方法。
@AfterClass:在运行当前类的所有测试方法后,将运行带注释的方法。
@BeforeMethod:在每个测试方法之前都会运行带注释的方法。
@AfterMethod:在每个测试方法之后,将运行带注释的方法。

alwaysrun   
在方法之前(beuite, beest, beforeTestClass和beforeTestMethod,但不是beforeGroups):如果设置为true,则将运行该配置方法,不管它属于哪个组。
对于after方法(afterSuite, afterClass,…):如果设置为true,这个配置方法将会运行,即使之前调用的一个或多个方法失败或被跳过。

dependsOnGroups 
此方法所依赖的组列表.

dependsOnMethods    
此方法所依赖的方法列表。

enabled 
是否启用了这个类/方法上的方法。

groups  
这个类/方法的组列表属于。
inheritGroups   
如果是true,该方法将属于类级别@Test注释中指定的组。

onlyForGroups   
只有@BeforeMethod和@AfterMethod。如果指定了,那么这个setup/teardown方法将只在对应的测试方法属于一个列出的组时才会被调用。

@DataProvider
标记方法为测试方法提供数据。带注释的方法必须返回一个对象[][],其中每个对象[]可以被分配到测试方法的参数列表。想要从这个DataProvider中接收数据的@Test方法需要使用DataProvider名称,它等于这个注释的名称。
name 此数据提供程序的名称。如果没有提供,这个数据提供程序的名称将自动被设置为方法的名称。
parallel 如果设置为true,使用此数据提供程序生成的测试将并行运行。默认值是错误的。

@Factory
标记一个方法,作为返回将被TestNG用作测试类的对象的工厂。该方法必须返回对象[]。

@Listeners 在测试类中定义侦听器。
value 一组扩展了org.testng.ITestNGListener的类。

@Parameters 描述如何将参数传递给@Test方法。
value 用于填充该方法参数的变量列表。

@Test 标记一个类或方法作为测试的一部分。
alwaysRun 如果设置为true,这个测试方法将始终运行,即使它依赖于失败的方法。
dataProvider 此测试方法的数据提供程序的名称。
dataProviderClass 要查找数据提供程序的类。如果没有指定,数据提供程序将被查看当前测试方法的类或它的一个基类。如果指定此属性,则数据提供程序方法需要在指定的类上保持静态。
dependsOnGroups 此方法所依赖的组列表。
dependsOnMethods 此方法所依赖的方法列表。
description 此方法的描述。
enabled 是否启用了这个类/方法上的方法。
expectedExceptions 测试方法预期抛出的异常列表。如果在这个列表中没有一个异常或一个不同,那么这个测试将被标记为失败。
groups 这个类/方法的组列表属于。
invocationCount 应该调用此方法的次数。
invocationTimeOut 这个测试的最大毫秒数应该用于所有调用的累积时间。如果未指定invocationCount,该属性将被忽略。
priority 此测试方法的优先级。较低的优先次序将优先安排。
successPercentage 预期成功的百分比。
singleThreaded 如果设置为true,那么在这个测试类上的所有方法都保证在同一个线程中运行,即使当前运行的测试是并行的=“方法”。此属性只能在类级别使用,如果在方法级别使用,则将被忽略。注意:这个属性以前被称为序列(现在已弃用)。
timeOut 这个测试应该使用的最大毫秒数。
threadPoolSize 该方法的线程池的大小。该方法将由invocationCount指定的多个线程调用。如果未指定invocationCount,该属性将被忽略。

3 - testng.xml
可以用几种不同的方式调用TestNG:
testng.xml文件
ant
cmd

//测试

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite1" verbose="1" >
  <test name="Nopackage" >
    <classes>
       <class name="NoPackageTest" />
    </classes>
  </test>
  <test name="Regression1">
    <classes>
      <class name="test.sample.ParameterSample"/>
      <class name="test.sample.ParameterTest"/>
    </classes>
  </test>
</suite>

//包内部

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite1" verbose="1" >
  <test name="Regression1"   >
    <packages>
      <package name="test.sample" />
   </packages>
 </test>
</suite>

//在本例中,TestNG将查看包测试中的所有类。示例并将只保留具有TestNG注释的类。
//您还可以指定包含和排除的组和方法:


<test name="Regression1">
  <groups>
    <run>
      <exclude name="brokenTests"  />
      <include name="checkinTests"  />
    </run>
  </groups>

  <classes>
    <class name="test.IndividualMethodsTest">
      <methods>
        <include name="testMethod" />
      </methods>
    </class>
  </classes>
</test>

//您还可以在testng中定义新的组。xml并在属性中指定额外的细节,比如是否并行运行测试、使用多少线程、是否运行JUnit测试等等……
//在默认情况下,TestNG将按照在XML文件中找到的顺序运行测试。如果您希望在这个文件中列出的类和方法以不可预测的顺序运行,则将preserorder属性设置为false。

<test name="Regression1" preserve-order="false">
  <classes>

    <class name="test.Test1">
      <methods>
        <include name="m1" />
        <include name="m2" />
      </methods>
    </class>

    <class name="test.Test2" />

  </classes>
</test>

4 - Running TestNG
//本节只说明如何从命令行调用TestNG。如果你对另一种方式感兴趣,请点击上面的链接。
//假设在类路径中有TestNG,调用TestNG的最简单方法如下:
java org.testng.TestNG testng1.xml [testng2.xml testng3.xml …]

5 - Test methods, Test classes and Test groups
5.1 - Test methods
测试方法用@Test进行注释。如果您在testng.xm中为true设置了allow- returnvalues,那么使用@Test来注释的方法将会被忽略。

<suite allow-return-values="true"> 
or
<test allow-return-values="true">

5.2 - Test groups
TestNG允许您执行复杂的测试方法分组。您不仅可以声明方法属于组,还可以指定包含其他组的组。然后TestNG可以调用和要求包括一个特定的团体(或表达式),而不包括另一组。这给了你最大的灵活性分区测试,不需要你重新编译任何东西,如果你想运行两个不同的测试。

//组运行

public class Test1 {
  @Test(groups = { "functest", "checkintest" })
  public void testMethod1() {
  }

  @Test(groups = {"functest", "checkintest"} )
  public void testMethod2() {
  }

  @Test(groups = { "functest" })
  public void testMethod3() {
  }
}

<test name="Test1">
  <groups>
    <run>
      <include name="functest"/>
    </run>
  </groups>
  <classes>
    <class name="example1.Test1"/>
  </classes>
</test>


//@Test
public class Test1 {
  @Test(groups = { "windows.checkintest" })
  public void testWindowsOnly() {
  }

  @Test(groups = {"linux.checkintest"} )
  public void testLinuxOnly() {
  }

  @Test(groups = { "windows.functest" )
  public void testWindowsToo() {
  }
}

<test name="Test1">
  <groups>
    <run>
      <include name="windows.*"/>
    </run>
  </groups>

  <classes>
    <class name="example1.Test1"/>
  </classes>
</test>


Method groups
<test name="Test1">
  <classes>
    <class name="example1.Test1">
      <methods>
        <include name=".*enabledTestMethod.*"/>
        <exclude name=".*brokenTestMethod.*"/>
      </methods>
     </class>
  </classes>
</test>

5.3 - Groups of groups

<test name="Regression1">
  <groups>
    <define name="functest">
      <include name="windows"/>
      <include name="linux"/>
    </define>

    <define name="all">
      <include name="functest"/>
      <include name="checkintest"/>
    </define>

    <run>
      <include name="all"/>
    </run>
  </groups>

  <classes>
    <class name="test.sample.Test1"/>
  </classes>
</test>

5.4 - Exclusion groups
5.5 - Partial groups
5.6 - Parameters
5.6.1 - Parameters from testng.xml

5.6.2 - Parameters with DataProviders 可用来设置延迟时间

//This method will provide data to any test method that declares that its Data Provider
//is named "test1"
@DataProvider(name = "test1")
public Object[][] createData1() {
 return new Object[][] {
   { "Cedric", new Integer(36) },
   { "Anne", new Integer(37)},
 };
}

//This test method declares that its data should be supplied by the Data Provider
//named "test1"
@Test(dataProvider = "test1")
public void verifyData1(String n1, Integer n2) {
 System.out.println(n1 + " " + n2);
}

5.6.3 - Parameters in reports

5.7 - Dependencies
TestNG允许您用注释或XML指定依赖项。

5.7.1 - Dependencies with annotations

有两种依赖性:
Hard 艰难的依赖关系。您所依赖的所有方法都必须运行并成功地运行。如果在您的依赖项中发生至少一次失败,您将不会被调用,并在报告中标记为跳过。
Soft 柔软的依赖关系。您将始终在您所依赖的方法之后运行,即使有些方法失败了。当您只想确保您的测试方法是按照一定的顺序运行时,这是很有用的,但是它们的成功并不依赖于其他的成功。通过在@Test注释中添加“alwaysRun=true”来获得一个软的依赖关系。

5.7.2 - Dependencies in XML

<test name="My suite">
  <groups>
    <dependencies>
      <group name="c" depends-on="a  b" />
      <group name="z" depends-on="c" />
    </dependencies>
  </groups>
</test>

5.8 - Factories (学习查看)

5.9 - Class level annotations

5.10 - Ignoring tests
TestNG lets you ignore all the @Test methods :
TestNG允许您忽略所有@Test方法:
In a class (or)
在一个类(或)
In a particular package (or)
在一个特定的包中(或)
In a package and all of its child packages
在一个包和所有的子包中。

5.11 - Parallelism and time-outs
您可以指导TestNG在不同的线程中以不同的方式运行您的测试。
java org.testng.TestNG -suitethreadpoolsize 3 testng1.xml testng2.xml testng3.xml

5.11.2 - Parallel tests, classes and methods

<suite name="My suite" parallel="methods" thread-count="5">
允许所有方法是相同线程,其他parallel级别的为不同线程
<suite name="My suite" parallel="tests" thread-count="5">
<suite name="My suite" parallel="classes" thread-count="5">
<suite name="My suite" parallel="instances" thread-count="5">

http://testng.org/doc/documentation-main.html
@Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000)
public void testServer()
在本例中,函数testServer将从三个不同的线程调用10次。此外,10秒的超时保证了所有线程都不会永远阻塞这个线程。

5.12 - Rerunning failed tests
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs testng.xml
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs test-outputs\testng-failed.xml

5.13 - JUnit tests
TestNG可以运行JUnit 3和JUnit 4测试。您需要做的就是将JUnit jar文件放在类路径上,在testng中指定您的JUnit测试类。
classname属性并设置testng。junit属性为true:


5.14 - Running TestNG programmatically 运行TestNG编程

TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { Run2.class });
testng.addListener(tla);
testng.run();

创建虚拟的testNg文件来测试






模板:
XmlSuite suite = new XmlSuite();
suite.setName(“TmpSuite”);

XmlTest test = new XmlTest(suite);
test.setName(“TmpTest”);
List classes = new ArrayList();
classes.add(new XmlClass(“test.failures.Child”));
test.setXmlClasses(classes) ;

List suites = new ArrayList();
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();

5.15 - BeanShell and advanced group selection
筛选进行测试,包含script,则该test内部优先选择script来区分测试,无效

<test name="BeanShell test">
   <method-selectors>
     <method-selector>
       <script language="beanshell"><![CDATA[
         groups.containsKey("test1")
       ]]></script>
     </method-selector>
   </method-selectors>
  <!-- ... -->

java.lang.reflect.Method method: the current test method.
org.testng.ITestNGMethod testngMethod: the description of the current test method.
java.util.Map

public class MyTransformer implements IAnnotationTransformer {
  public void transform(ITest annotation, Class testClass,
      Constructor testConstructor, Method testMethod)
  {
    if ("invoke".equals(testMethod.getName())) {
      annotation.setInvocationCount(5);
    }
  }
}

5.17 - Method Interceptors 方法拦截器
一旦TestNG计算了测试方法将被调用的顺序,这些方法分为两组:
方法按顺序运行。这些都是有依赖关系或依赖关系的测试方法。这些方法将以特定的顺序运行。
方法不按特定顺序运行。这些都是不属于第一类的方法。这些测试方法运行的顺序是随机的,并且可以从一个运行到另一个运行(尽管在默认情况下,TestNG将尝试按类分组测试方法)。
为了给你更多的控制方法的归属。

public interface IMethodInterceptor {
  List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context);
}

在参数中传递的方法列表是可以按任何顺序运行的所有方法。您的拦截方法将返回一个类似的IMethodInstance列表,它可以是以下任何一个:
您在参数中收到的相同列表,但顺序不同。
一个较小的IMethodInstance对象列表。
一个更大的isystemdinstance对象列表。
一旦定义了拦截器,就将它传递给TestNG作为侦听器。例如:

java -classpath "testng-jdk15.jar:test/build" org.testng.TestNG -listener test.methodinterceptors.NullMethodInterceptor
   -testclass test.methodinterceptors.FooTest

public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
  List<IMethodInstance> result = new ArrayList<IMethodInstance>();
  for (IMethodInstance m : methods) {
    Test test = m.getMethod().getConstructorOrMethod().getAnnotation(Test.class);
    Set<String> groups = new HashSet<String>();
    for (String group : test.groups()) {
      groups.add(group);
    }
    if (groups.contains("fast")) {
      result.add(0, m);
    }
    else {
      result.add(m);
    }
  }
  return result;
}

5.18 - TestNG Listeners

IAnnotationTransformer (doc, javadoc)
IAnnotationTransformer2 (doc, javadoc)
IHookable (doc, javadoc)
IInvokedMethodListener (doc, javadoc)
IMethodInterceptor (doc, javadoc)
IReporter (doc, javadoc)
ISuiteListener (doc, javadoc)
ITestListener (doc, javadoc) 

Using -listener on the command line.
Using <listeners> with ant.
Using <listeners> in your testng.xml file.
Using the @Listeners annotation on any of your test classes.
Using ServiceLoader. 

5.18.1 - Specifying listeners with testng.xml or in Java

<suite>

  <listeners>
    <listener class-name="com.example.MyListener" />
    <listener class-name="com.example.MyMethodInterceptor" />
  </listeners>

...

@Listeners({ com.example.MyListener.class, com.example.MyMethodInterceptor.class })
public class MyTest {
  // ...
}   

The @Listeners annotation can contain any class that extends org.testng.ITestNGListener except IAnnotationTransformer and IAnnotationTransformer2.

5.18.2 - Specifying listeners with ServiceLoader
serverLoad通过jar文件去找testng和testng.xml

package test.tmp;

public class TmpSuiteListener implements ISuiteListener {
  @Override
  public void onFinish(ISuite suite) {
    System.out.println("Finishing");
  }

  @Override
  public void onStart(ISuite suite) {
    System.out.println("Starting");
  }
}
Compile this file, then create a file at the location META-INF/services/org.testng.ITestNGListener, which will name the implementation(s) you want for this interface.

You should end up with the following directory structure, with only two files:
$ tree
|____META-INF
| |____services
| | |____org.testng.ITestNGListener
|____test
| |____tmp
| | |____TmpSuiteListener.class

$ cat META-INF/services/org.testng.ITestNGListener
test.tmp.TmpSuiteListener
Create a jar of this directory:
$ jar cvf ../sl.jar .
added manifest
ignoring entry META-INF/
adding: META-INF/services/(in = 0) (out= 0)(stored 0%)
adding: META-INF/services/org.testng.ITestNGListener(in = 26) (out= 28)(deflated -7%)
adding: test/(in = 0) (out= 0)(stored 0%)
adding: test/tmp/(in = 0) (out= 0)(stored 0%)
adding: test/tmp/TmpSuiteListener.class(in = 849) (out= 470)(deflated 44%)
Next, put this jar file on your classpath when you invoke TestNG:
$ java -classpath sl.jar:testng.jar org.testng.TestNG testng-single.yaml
Starting
f2 11 2
PASSED: f2("2")
Finishing

5.19 - Dependency injection
TestNG支持两种不同类型的依赖注入:本机(由TestNG本身执行)和外部(由依赖注入框架(如Guice)执行)。

5.19.1 -本地依赖注入。
TestNG允许您在方法中声明其他参数。当发生这种情况时,TestNG将自动地将这些参数填入正确的值。依赖注入可以在以下地方使用:
任何@Before方法或@Test方法都可以声明类型ITestContext的参数。
任何@AfterMethod方法都可以声明一个ITestResult类型的参数,它将反映刚刚运行的测试方法的结果。
任何@Before和@After方法(@ beuite和@AfterSuite除外)都可以声明一个XmlTest类型的参数,该参数包含当前标记。

public class NoInjectionTest {

  @DataProvider(name = "provider")
  public Object[][] provide() throws Exception {
      return new Object[][] { { CC.class.getMethod("f") } };
  }

  @Test(dataProvider = "provider")
  public void withoutInjection(@NoInjection Method m) {
      Assert.assertEquals(m.getName(), "f");
  }

  @Test(dataProvider = "provider")
  public void withInjection(Method m) {
      Assert.assertEquals(m.getName(), "withInjection");
  }
}

下表总结了可以为各种TestNG注释本机注入的参数类型:
Annotation   ITestContext    XmlTest     Method      Object[]    ITestResult 
BeforeSuite     Yes             No          No          No          No
BeforeTest  Yes             Yes         No          No          No
BeforeGroups    Yes             Yes         No          No          No
BeforeClass     Yes             Yes         No          No          No
BeforeMethod    Yes             Yes         Yes         Yes         Yes
Test        Yes             No          No          No          No
DataProvider    Yes             No          Yes         No          No
AfterMethod     Yes             Yes         Yes         Yes         Yes
AfterClass  Yes             Yes         No          No          No
AfterGroups     Yes             Yes         No          No          No
AfterTest   Yes             Yes         No          No          No
AfterSuite  Yes     No      No          No          No          No

5.19.2 - Guice dependency injection Guice依赖注入

@Guice(modules = GuiceExampleModule.class)
public class GuiceTest extends SimpleBaseTest {

  @Inject
  ISingleton m_singleton;

  @Test
  public void singletonShouldWork() {
    m_singleton.doSomething();
  }

}

public class GuiceExampleModule implements Module {

  @Override
  public void configure(Binder binder) {
    binder.bind(ISingleton.class).to(ExampleSingleton.class).in(Singleton.class);
  }

}

@Guice(moduleFactory = ModuleFactory.class)
public class GuiceModuleFactoryTest {

  @Inject
  ISingleton m_singleton;

  @Test
  public void singletonShouldWork() {
    m_singleton.doSomething();
  }
}

public interface IModuleFactory {
 /**
   * @param context The current test context
   * @param testClass The test class
   *
   * @return The Guice module that should be used to get an instance of this
   * test class.
   */
  Module createModule(ITestContext context, Class<?> testClass);
}

<suite parent-module="com.example.SuiteParenModule" guice-stage="PRODUCTION">
</suite>

package com.example;

public class ParentModule extends AbstractModule {
  @Override
  protected void conigure() {
    bind(MyService.class).toProvider(MyServiceProvider.class);
    bind(MyContext.class).to(MyContextImpl.class).in(Singleton.class);
  }
}

package com.example;

public class TestModule extends AbstractModule {
  private final MyContext myContext;

  @Inject
  TestModule(MyContext myContext) {
    this.myContext = myContext
  }

  @Override
  protected void configure() {
    bind(MySession.class).toInstance(myContext.getSession());
  }
}
<suite parent-module="com.example.ParentModule">
</suite>
package com.example;

@Test
@Guice(modules = TestModule.class)
public class TestClass {
  @Inject
  MyService myService;
  @Inject
  MySession mySession;

  public void testServiceWithSession() {
    myService.serve(mySession);
  }
}

5.20 - Listening to method invocations
侦听器IInvokedMethodListener允许您在TestNG即将调用一个测试(用@Test进行注释)
或配置(使用@Before或@After注释)方法时通知您。您需要实现以下接口:

public interface IInvokedMethodListener extends ITestNGListener {
  void beforeInvocation(IInvokedMethod method, ITestResult testResult);
  void afterInvocation(IInvokedMethod method, ITestResult testResult);
}

5.21 - Overriding test methods
TestNG允许您重写并可能跳过对测试方法的调用。如果您需要与特定的安全管理器进行测试,
那么其中一个有用的例子就是。您通过提供实现IHookable的侦听器来实现这一点

public class MyHook implements IHookable {
  public void run(final IHookCallBack icb, ITestResult testResult) {
    // Preferably initialized in a @Configuration method
    mySubject = authenticateWithJAAs();

    Subject.doAs(mySubject, new PrivilegedExceptionAction() {
      public Object run() {
        icb.callback(testResult);
      }
    };
  }
}

5.22 - Altering suites (or) tests
有时候,您可能需要在运行时更改一个suite.xml中的一个测试标记,而不需要更改一个套件文件的内容。
一个典型的例子是尝试利用现有的套件文件,并尝试使用它来模拟“正在测试的应用程序”上的负载测试。至少,您可以多次复制<测试>标记的内容,并创建一个新的suite xml文件并与之一起工作。但这似乎并没有很多。
TestNG允许您在运行时通过侦听器更改套件xml文件中的一个测试标记。你大力开展

public class AlterSuiteNameListener implements IAlterSuiteListener {

    @Override
    public void alter(List<XmlSuite> suites) {
        XmlSuite suite = suites.get(0);
        suite.setName(getClass().getSimpleName());
    }
}

6 - Test results
6.1 - Success, failure and assert
如果测试在完成时没有抛出任何异常,或者抛出了预期的异常(参见@Test注释中所发现的期望属性的文档),那么测试就会被认为是成功的。
您的测试方法通常由可以抛出异常的调用或各种断言组成(使用Java“assert”关键字)。“assert”失败会触发AssertionErrorException,而这又会将该方法标记为failed(如果您没有看到断言错误,请记住在JVM上使用-ea)。
下面是一个示例测试方法:

@Test
public void verifyLastName() {
  assert "Beust".equals(m_lastName) : "Expected name Beust, for" + m_lastName;
}

import static org.testng.AssertJUnit.*;
//...
@Test
public void verify() {
  assertEquals("Beust", m_lastName);
}

6.2 - Logging and results
测试运行的结果在一个名为index的文件中创建。在启动SuiteRunner时指定的目录中的html。
该文件指向包含整个测试运行结果的各种其他HTML和文本文件。
你可以很容易地用TestNG来生成你自己的报告,监听和记者:
侦听器实现了接口org.testng。当测试启动、传递、失败等时,它会被实时通知。
记者实现了界面的功能。当所有的套件都由TestNG运行时,IReporter会得到通知。IReporter实例接收描述整个测试运行的对象列表。

例如,如果您想要生成测试运行的PDF报告,那么您不需要在测试运行的实际时间内得到通知,因此您应该使用IReporter。
如果您想要编写测试的实时报告,比如使用进度条的GUI,或者在调用每个测试时显示点(“.”),那么它是您最好的选择。

6.2.1 - Logging Listeners
这里是一个显示“.”的监听器,每个测试都有一个“F”,每个失败都有一个“S”。

public class DotTestListener extends TestListenerAdapter {
  private int m_count = 0;

  @Override
  public void onTestFailure(ITestResult tr) {
    log("F");
  }

  @Override
  public void onTestSkipped(ITestResult tr) {
    log("S");
  }

  @Override
  public void onTestSuccess(ITestResult tr) {
    log(".");
  }

  private void log(String string) {
    System.out.print(string);
    if (++m_count % 40 == 0) {
      System.out.println("");
    }
  }
} 

在这个例子中,我选择扩展TestListenerAdapter,它用空的方法实现了ITestListener,因此我不必从我不感兴趣的接口中重写其他方法。如果您愿意,可以直接实现接口。
下面是我如何调用TestNG来使用这个新侦听器:
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener org.testng.reporters.DotTestListener test\testng.xml

6.2.2 - Logging Reporters org.testng.IReporter
public void generateReport(List suites, String outputDirectory)

6.2.3 - JUnitReports
TestNG中包含一个监听器,它接受TestNG结果并输出一个XML文件,然后将其输入JUnitReport。
下面是一个示例,以及创建该报告的ant任务:

<target name="reports">
  <junitreport todir="test-report">
    <fileset dir="test-output">
      <include name="*/*.xml"/>
    </fileset>

    <report format="noframes"  todir="test-report"/>
  </junitreport>
</target>

6.2.4 - Reporter API
如果您需要记录在生成的HTML报告中应该出现的消息,您可以使用类org.testng.Reporter:
Reporter.log(“M3 WAS CALLED”);

6.2.5 - XML Reports
TestNG提供了一个XML reporter,它捕获了JUnit报告中不可用的TestNG特定信息。当用户的测试环境需要使用JUnit格式无法提供的testng特定数据时
这一点特别有用。该记者可以通过与记者的命令行注入TestNG。

    : - to separate the reporter name from its properties
    = - to separate key/value pairs for properties
    , - to separate multiple key/value pairs

<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>

该报告将与其他缺省监听器一起注入,这样您就可以在默认情况下获得这种类型的输出。侦听器提供了一些属性,
可以调整reporter以满足您的需要。下表包含了这些属性的列表,其中有一个简短的解释:
outputDirectory 输出目录
timestampFormat 日期时间
fileFragmentationLevel 1 -将在一个文件中生成所有结果。2 -每个套件都是在一个与主文件相连的单独的XML文件中生成的。3 -与2 plus单独的文件,用于从套件文件中引用的测试用例。
splitClassAndPackageNames 是否获得类标签 true or false
generateGroupsAttribute 是否生成组苏醒
stackTraceOutputMethod 0 -没有stacktrace(只有异常类和消息)。1 -一个短版本的堆栈跟踪,只保留几行从顶部。
2 -所有内部异常的完整堆栈跟踪。3 -短而长的堆栈跟踪。
generateDependsOnMethods 使用此属性可为元素启用/禁用依赖方法属性的生成。
generateDependsOnGroups 启用/禁用依赖组属性对于属性

7 - YAML
8 - Dry Run for your tests
当在dry run模式下启动时,TestNG将显示一个测试方法的列表,该列表将被调用,但实际上并没有调用它们。
您可以通过传递JVM参数-Dtestng.mode.dryrun=true来启用TestNG的dryrun模式。

Uhost对testNG测试总结:
1、流程:服务端发送相关信息数据,客户端接收到相关信息数据。
2、执行方式:执行testng.xml 执行测试组javaClass。
3、无法调用不存在的类,相同的类(测试类已固定)。
4、类似python的noseTest框架,一个萝卜一个坑,做测试方法执行。
5、无法在testng.xml内部测试用例类,因为java无法重新生成和编译成自己码文件。
6、同类里面排除方法
7、综合分析:需要已知或配置好所有的测试用例类,然后根据消息传过来进行筛选测试方法测试或者不测试。

针对AT,一个测试用例类,包含所有测试方法,根据消息进行测试用例排除,新增的话就需要新增测试方法。
也不是可扩展自定义类型(自定义扩展方式:adb直接获取执行进行读取,不可控异常,(可扩展,无测试框架稳定))。
或者xlsx文件配置。

针对.bat .sh类的文件类型的测试用例:
无法纳入TestNG测试框架,循环遍历搜索匹配测试用例进行执行。手机异常状态不可控和实现。(如果存放于一个APK,权限)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值