`

testng 笔记

    博客分类:
  • test
阅读更多

 

 

1.overview

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use, such as:

  • JDK 5 Annotations (JDK 1.4 is also supported with JavaDoc annotations).
  • Support for data-driven testing (with @DataProvider ).
  • Support for parameters.
  • Embeds BeanShell for further flexibility.
  • Default JDK functions for runtime and logging (no dependencies).
  • Dependent methods for application server testing.

 

 

Here is a very simple test:

package example1;

 

import org.testng.annotations.*;

 

public class SimpleTest {

 

 @BeforeClass

 public void setUp() {

   

// code that will be invoked when this test is instantiated

 }

 

 @Test(groups = { "fast" })

 public void aFastTest() {

   

System.out.println("Fast test");

 }

 

 @Test(groups = { "slow" })

 public void aSlowTest() {

    

System.out.println("Slow test");

 }

 

}

 

 

 

ant.xml

 

<project default="test">

 

  <path id="cp">

   <pathelement location="lib/testng-testng-4.4-jdk15.jar"/>

   <pathelement location="build"/>

  </path>

 

  <taskdef name="testng" classpathref="cp"

          classname="org.testng.TestNGAntTask" />

 

  <target name="test">

   <testng classpathref="cp" groups="fast">

     <classfileset dir="build" includes="example1/*.class"/>

   </testng>

  </target>

 

</project>

 

 

 

 

 

 

Here is a quick overview of the annotations available in TestNG along with their attributes.

@BeforeSuite
@AfterSuite
@BeforeTest
@AfterTest
@BeforeGroups
@AfterGroups
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod

Configuration information for a TestNG class:

@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeTest : The annotated method will be run before the test.
@AfterTest : The annotated method will be run after the test.
@BeforeGroups : The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups : The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@BeforeClass : The annotated method will be run before the first test method in the current class is invoked.
@AfterClass : The annotated method will be run after all the test methods in the current class have been run.
@BeforeMethod : The annotated method will be run before each test method.
@AfterMethod : The annotated method will be run after each test method.

 

alwaysRun

For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to.
For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.

 

dependsOnGroups

The list of groups this method depends on.

 

dependsOnMethods

The list of methods this method depends on.

 

enabled

Whether methods on this class/method are enabled.

 

groups

The list of groups this class/method belongs to.

 

inheritGroups

If true, this method will belong to groups specified in the @Test annotation at the class level.

 

@DataProvider

Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.

 

name

The name of this DataProvider.

 

@Factory

Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[].

 

@Parameters

Describes how to pass parameters to a @Test method.

 

value

The list of variables used to fill the parameters of this method.

 

@Test

Marks a class or a method as part of the test.

 

alwaysRun

If set to true, this test method will always be run even if it depends on a method that failed.

 

dataProvider

The name of the data provider for this test method.

 

dataProviderClass

The class where to look for the data provider. If not specified, the data provider will be looked on the class of the current test method or one of its base classes. If this attribute is specified, the data provider method needs to be static on the specified class.

 

dependsOnGroups

The list of groups this method depends on.

 

dependsOnMethods

The list of methods this method depends on.

 

description

The description for this method.

 

enabled

Whether methods on this class/method are enabled.

 

expectedExceptions

The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.

 

groups

The list of groups this class/method belongs to.

 

invocationCount

The number of times this method should be invoked.

 

invocationTimeOut

The maximum number of milliseconds this test should take for the cumulated time of all the invocationcounts. This attribute will be ignored if invocationCount is not specified.

 

successPercentage

The percentage of success expected from this method

 

sequential

If set to true, all the methods on this test class are guaranteed to run sequentially, even if the tests are currently being run with parallel="methods". This attribute can only be used at the class level and it will be ignored if used at the method level.

 

timeOut

The maximum number of milliseconds this test should take.

 

threadPoolSize

The size of the thread pool for this method. The method will be invoked from multiple threads as specified by invocationCount.
Note: this attribute is ignored if invocationCount is not specified

 

 

 

public class Test1 {

  

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

  

public void testMethod1() {

  

}

 

  

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

  

public void testMethod2() {

  

}

 

  

@Test(groups = { "functest" })

  

public void testMethod3() {

  

}

}

Invoking TestNG with

<test name="Test1">

  

<groups>

    

<run>

      

<include name="functest"/>

    

</run>

  

</groups>

  

<classes>

    

<class name="example1.Test1"/>

  

</classes>

</test>

 

 

a test method or class could be unit test, dao test, regression test at the same time.

 

 

 

Here is another example, using regular expressions this time.  Assume that some of your test methods should not be run on Linux, your test would look like:

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

  

}

}

You could use the following testng.xml to launch only the Windows methods:

<test name="Test1">

  

<groups>

    

<run>

      

<include name="windows.*"/>

    

</run>

  

</groups>

 

  

<classes>

    

<class name="example1.Test1"/>

  

</classes>

</test>

Note: TestNG uses regular expressions , and not wildmats . Be aware of the difference (for example, "anything" is matched by ".*" -- dot star -- and not "*").

 

 

You can also exclude or include individual methods:

<test name="Test1">

  <classes>

    <class name="example1.Test1">

      <methods>

        <include name=".*enabledTestMethod.*"/>

        <exclude name=".*brokenTestMethod.*"/>

      </methods>

     </class>

  </classes>

</test>

 

 

You can define groups at the class level and then add groups at the method level:

@Test(groups = { "checkin-test" })

public class All {

 

  @Test(groups = { "func-test" )

  public void method1() { ... }

 

  public void method2() { ... }

}

In this class, method2() is part of the group "checkin-test", which is defined at the class level, while method1() belongs to both "checkin-test" and "func-test".

 

 

@Parameters({ "first-name" })

@Test

public void testSingleString(String firstName) { 

  

System.out.println("Invoked testString " + firstName);

  

assert "Cedric".equals(firstName);

}

<suite name="My suite">

  

<parameter name="first-name"  

value="Cedric"/>

  

<test name="Simple example">

  

<-- ... -->

 

 

The same technique can be used for @Before/After and @Factory annotations:

@Parameters({ "datasource", "jdbcDriver" })

@BeforeMethod

public void beforeTest(String ds, String driver) {

  

m_dataSource = ...;                    

          

// look up the value of datasource

  

m_jdbcDriver = driver;

}

 

@Parameters("db")

@Test

public void testNonExistentParameter(@Optional("mysql") String db) { ... }

If no parameter named "db" is found in your testng.xml file, your test method will receive the default value specified inside the @Optional annotation: "mysql".

 

 

@DataProvider(name = "test1")

public Object[][] createData1() {

 return new Object[][] {

   

{ "Cedric", new Integer(36) },

   

{ "Anne", new Integer(37)}, 

 

};

}

@Test(dataProvider = "test1")

public void verifyData1(String n1, Integer n2) {

 System.out.println(n1 + " " + n2);

} 

will print

Cedric 36

Anne 37

 

@Test(dataProvider = "test1",invocationCount=3)

    public void verifyData1(String n1, Integer n2) {

        System.out.println(n1 + " " + n2);

}

 

Total tests run: 6, Failures: 0, Skips: 0

 

By default, the data provider will be looked for in the current test class or one of its base classes. If you want to put your data provider in a different class, it needs to be a static method and you specify the class where it can be found in the dataProviderClass attribute:

public static class StaticProvider {

  

@DataProvider(name = "create")

  

public static Object[][] createData() {

    

return new Object[][] {

      

new Object[] { new Integer(42) }

    

}

  

}

}

 

public class MyTest {

  

@Test(dataProvider = "create", dataProviderClass = StaticProvider.class)

  

public void test(Integer n) {

    

// ...

  

}

}

 

ps. StaticProvider 不一定必须是static, 方法必须是static

  dataprovider提供的是一个二维数组,只算count一次

new Object[][] {

   

{ "Cedric", new Integer(36) }, 一组测试数据

   

{ "Anne", new Integer(37)},    

一组测试数据

 };

@DataProvider(parallel = true)

 

 

dependent on method

@Test

public void serverStartedOk() {}

 

@Test(dependsOnMethods = { "serverStartedOk" })

public void method1() {}

 

dependent on group

 

@Test(groups = { "init" })

public void serverStartedOk() {}

 

@Test(groups = { "init" })

public void initEnvironment() {}

 

@Test(dependsOnGroups = { "init.* })

public void method1() {}

 

public class WebTestFactory {

  

@Factory

  

public Object[] createInstances() {

   

Object[] result = new Object[10];  



   

for (int i = 0; i < 10; i++) {

      

result[i] = new WebTest(i * 10);

    

return result;

  

}

}

 

public class WebTest {

  

private int m_numberOfTimes;

  

public WebTest(int numberOfTimes) {

    

m_numberOfTimes = numberOfTimes;

  

}

 

  

@Test

  

public void testServer() {

   

for (int i = 0; i < m_numberOfTimes; i++) {

     

// access the web page

    

}

  

}

}

 

 

@Test(threadPoolSize = 3, invocationCount = 10,  

timeOut = 10000)

public void testServer() {

 

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

 

 

0
0
分享到:
评论

相关推荐

    TestNG笔记

    TestNG 是一个强大的自动化测试框架,受到JUnit和NUnit的启发,但增加了许多创新特性,使其更适合各种测试需求,包括单元、功能、端到端和集成测试。TestNG需要Java Development Kit (JDK) 5或更高版本才能运行。本...

    TestNG中文手册学习笔记

    TestNG 是一个强大的自动化测试框架,受到 JUnit 和 NUnit 的启发,但在功能和灵活性上有所增强,特别适合进行单元测试、功能测试、端到端测试和集成测试。它需要 JDK 5 或更高版本来运行。TestNG 的设计目标是为...

    TestNG学习笔记

    ### TestNG 学习笔记概览 #### 一、JUnit 的局限性与 TestNG 的优势 ##### JUnit 缺陷概述 - **最初的用途限制**:JUnit 最初被设计为一个仅适用于单元测试的框架,但随着时间的发展,其功能已扩展至支持多种类型...

    【TestNG自动化测试框架】TestNG自动化测试框架入门到实战完整笔记

    TestNG自动测试框架是当今流行的自动化测试框架之一 它可以帮助自动化测试工程师把精力集中在编写和实施测试用例和测试脚本上,提升软件测试执行和回归测试效率 分成4大模块 第一模块java 基础知识:JDK安装以及环境...

    Selenium+Eclipse+Junit+TestNG自动化学习笔记

    ### Selenium+Eclipse+JUnit+TestNG自动化测试学习笔记 #### 一、环境搭建与配置 **1. 安装 JDK** - **版本**: JDK 1.7 - **下载地址**: ...

    达内Java项目云笔记12天完整源码cloudnote_day12_all.zip

    11. **单元测试与集成测试**:为了确保代码质量,项目可能包含了JUnit或TestNG进行单元测试,而Spring Boot提供的MockMvc可用于模拟HTTP请求进行集成测试。 12. **版本控制**:项目可能使用Git进行版本控制,便于...

    云笔记资源代码

    测试是任何软件项目的重要组成部分,可能会使用JUnit或TestNG进行单元测试,确保每个独立的代码模块都能正常工作。而Spring Boot自带的MockMVC可以用来进行模拟HTTP请求的集成测试。 在部署方面,项目可能使用...

    ssh学习笔记

    - **spring-test**:提供了对 JUnit 或 TestNG 进行集成测试的支持。 - **junit**:一个常用的单元测试框架。 ### 二、数据库访问 #### Spring JDBC 模块 - **spring-jdbc**:提供了对 JDBC 的封装,使得数据访问...

    java学习笔记 良格格

    ### Java学习笔记要点 #### 一、了解Java ##### 1.1 Java的起源与发展历程 - **起源**: Java 最初是由 Sun 公司在 Green Project 中为了开发 Star7 应用程序而创建的一种编程语言。 - **命名**: 语言的名字来源于 ...

    软件测试内部教程笔记

    5. **自动化测试**:随着敏捷开发的普及,自动化测试工具如Selenium、JUnit、TestNG、Appium等的使用变得尤为重要。笔记会介绍如何创建测试脚本,进行回归测试,以及持续集成。 6. **性能测试**:包括负载测试、...

    Selenium WebDriver的笔记整理

    - 创建TestNG测试类:在Package中创建一个TestNG测试类,使用注解`@BeforeMethod`和`@AfterMethod`来定义测试前后的操作。 **编写测试代码** 1. 引入必要的类库,如`org.openqa.selenium.WebDriver`,`org.openqa....

    Java+JDK+6学习笔记.pdf

    - **测试工具**:JUnit、TestNG 等工具用于进行单元测试和集成测试。 - **项目库**:Maven Central Repository 等仓库提供大量的 Java 项目依赖。 - **论坛与文档**:Stack Overflow、Oracle Java 文档等资源对于...

    java体系笔记

    Eclipse、IntelliJ IDEA等IDE为Java开发提供了强大的集成环境,Maven或Gradle用于项目构建和依赖管理,Junit、TestNG等支持单元测试。 本Java体系笔记覆盖了从基础知识到高级特性的全面内容,帮助读者建立扎实的...

    Java+JDK6学习笔记(PDF版书籍,免费下载)

    ### Java+JDK6学习笔记知识点详解 #### 一、Java简介 - **起源与历史:** - 最初由Sun公司的Green Project发起,旨在创建一个名为Star7的应用程序编程语言。 - 名称来源于创始人James Gosling窗外的一棵橡树...

    web笔记两连发

    4. **开发工具**:标签中的"工具"可能指的是开发者在Web开发过程中使用的各种辅助软件,如IDE(IntelliJ IDEA、Eclipse)、版本控制系统(Git)、构建工具(Maven、Gradle)、调试器、测试框架(JUnit、TestNG)等。...

    Selenium学习笔记源代码

    5. **测试框架集成**:Selenium可以与JUnit、TestNG等测试框架结合,构建更复杂的测试套件。这样,你可以编写结构化的测试用例,方便管理和执行。 6. **浏览器模拟**:Selenium支持多种浏览器,如Chrome、Firefox、...

    Spring学习总结笔记

    - **Test**:支持测试Spring应用,包括JUnit和TestNG集成。 2. **Spring框架的搭建** 搭建Spring环境首先需要引入必要的依赖库,例如:aopalliance、commons-logging、spring-aop、spring-beans、spring-context...

    HSAE自动化工具,随手笔记

    5. 自动化测试套件:组织和管理多个测试用例,便于执行整个测试流程,例如JUnit或TestNG。 6. 报告和日志:提供详尽的测试结果,包括通过、失败、错误等信息,有助于问题定位和持续改进。 7. 集成与协作:与版本...

    IDEA快速使用入门笔记.zip

    同时,IDEA也支持JUnit和TestNG等单元测试框架,方便进行测试编写和运行。 9. **插件安装**: IDEA的扩展性极强,可以在"File" -&gt; "Settings" -&gt; "Plugins"中搜索并安装各种插件,以满足特定需求,如Lombok插件、...

    软件测试学习笔记001

    软件测试学习笔记001 software testing是软件生命周期中的一种质量保证活动,旨在评估软件产品是否满足要求和预期结果。software testing是软件开发过程中的一个重要步骤,可以帮助开发团队发现和修复软件中的错误...

Global site tag (gtag.js) - Google Analytics