一、 TestNG简介
TestNG是java中的一个测试框架,类似于Junit,功能类似,但是Junit更倾向于单个类的测试,主要用于单元测试;但是TestNG不局限于测试一个类,可以测试多个类,多个包,甚至多个外部框架组成的系统,可用于做单元测试,也可以用作集成测试。
一般来说,开发人员多用Junit做单元测试,测试人员多用TestNG做单元测试—持续集成测试。
TestNG使用步骤
1、编写测试业务逻辑,并添加TestNG annotation;
2、将待测试信息添加到testng.xml中;
3、运行TestNG。
TestNG运行方式
1、方式一:
右键要执行的方法,点击Run As --》TestNG Test
2、方式二:
通过testng.xml文件来执行,把要执行的case放到Testng.xml文件中。右键点击testng.xml,点击Run As--》TestNG Suite
3、方式三:
使用ant构建
4、方式四:
使用maven自动构建
二、TestNG安装
离线安装
1、Eclipse插件下载:
http://testng.org/doc/download.html
2、将插件放到eclipse的plugins文件夹下;
3、启动eclipse,点击helpàinstall new software,选择插件,install;
4、重启eclipse。
在线安装
1、选择菜单:HelpàInstall New Software,弹出的窗口中输入:
2、点击add按钮,选中TestNG后点击下一步即可;
3、重启eclipse。
三、基本注解
注解 |
描述 |
@BeforeSuite |
被注解的方法将在所有测试运行前运行 |
@AfterSuite |
被注解的方法将在所有测试运行后运行 |
@BeforeClass |
被注解的方法将在当前类的第一个测试方法调用前运行 |
@AfterClass |
被注解的方法将在当前类的最后一个测试方法调用后运行 |
@BeforeTest |
被注解的方法将在测试运行前运行 |
@AfterTest |
被注解的方法将在测试运行后运行 |
@BeforeGroups |
被注解的方法将在groups前执行。这个方法将在groups组中的第一个测试方法调用前执行 |
@AfterGroups |
被注解的方法将在groups后执行。这个方法将在groups组红的最后一个测试方法调用后执行 |
@BeforeMethod |
被注解的方法将在每一个测试方法调用前运行 |
@AfterMethod |
被注解的方法将在每一个测试方法调用后运行 |
@DataProvider |
被注解的方法用于为测试方法提供测试数据;使用测试数据的方法需要指向该注解 |
@Factory |
标记方法作为一个返回对象的工厂,这些对象将被TestNG用于作为测试类,这个方法必须返回Object[] |
@Parameters |
描述如何传递参数给@Test方法 |
@Test |
标记一个类或方法作为测试的一部分 |
示例一:
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TestActionATest {
@Test
public void testCase1() {
System.out.println("in test case 1");
}
@Test
public void testCase2() {
System.out.println("in test case 2");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("in beforeMethod");
}
@AfterMethod
public void afterMethod() {
System.out.println("in afterMethod");
}
@BeforeClass
public void beforeClass() {
System.out.println("in beforeClass");
}
@AfterClass
public void afterClass() {
System.out.println("in afterClass");
}
@BeforeTest
public void beforeTest() {
System.out.println("in beforeTest");
}
@AfterTest
public void afterTest() {
System.out.println("in afterTest");
}
@BeforeSuite
public void beforeSuite() {
System.out.println("in beforeSuite");
}
@AfterSuite
public void afterSuite() {
System.out.println("in afterSuite");
}
}
输出结果: