一、 概论
1.编写测试业务逻辑,并且在你的代码中插入 TestNG annotations 。
2.在 testng.xml 或 build.xml 添加你的测试信息。例如类名,希望运行的组等等
3.运行TestNG.
文档中会使用到如下的概念:
1.一套测试(suite)由一个XML文件所表示。它能够包含一个或者多个测试,<suite> 标记来定义。
2.
test由<test>标记来表示一个测试,并且可以包含一个或者多个TestNG类。
3.TestNG 类是包含至少一个TestNG annotation的java类,由<class>标签描述并包含一个或多个测试方法。
4.测试方法,就是一个普通的Java方法,在由@Test标记。
testNG.xml
testNG的运行需要一个配置文件,默认为testng.xml,其描述了要运行哪些测试等配置。
编写
testNG.xml如果没有书写提示,给在头部引入
<!DOCTYPE
suite
PUBLIC
"--//beust.com//testng//testng
1.0//EN"
"http://beust.com/testng/testng-1.0.dtd"
>就会有提示了
注意:TestNG使用的是 正则表达式,而不是通配符。注意这二者的区别
例如:"anything" 是匹配于 ".*" -- 点和星号 -- 而不是星号 "*"
![](https://img-my.csdn.net/uploads/201208/14/1344909702_6710.jpg)
Groups
testNG可以将各个method存放在不同的group里面,然后运行的时候可以指定要运行的group。Group指定的方式如下:
@Test(groups = {"fast", "unit", "database" })
public voidrowShouldBeInserted() {}
二、实例
1.创建测试类Sum
![](https://img-my.csdn.net/uploads/201208/14/1344909711_9937.jpg)
2.创建TestNG类
package com.testNg;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import com.hpp.Sum;
public class NewTest {
private Sum newSum = new Sum();
@Test(groups = { "t1", "t2" })
public void f() {
int mysum = newSum.add(1, 2);
assertEquals(3, mysum, "Right");
}
@Test(groups = { "t2" })
public void f2() {
int mysum = newSum.add(2, 2);
assertEquals(3, mysum, "Right");// 错误的用例
}
@Test(groups = { "t1" })
public void f3() {
int mysum = newSum.add(1, 2);
assertEquals(3, mysum, "Right");
}
}
3.修改
testNG.xml
<?xml version="1.0"encoding="UTF-8"?>
<suite name="Suite" parallel="false">
<testname = Test ">
<groups>
<run>
<includename = t1 " />
</run>
</groups>
<classes>
<classname = com.testNg.NewTest " />
</classes>
</test><!-- Test -->
</suite> <!--Suite -->
当
运行t1测试组时,就仅仅运行f()和f3()方法
运行结果
![](https://img-my.csdn.net/uploads/201208/14/1344909721_3919.jpg)
![](https://img-my.csdn.net/uploads/201208/14/1344909732_2343.jpg)
修改 testNG.xml运行t2测试组,其中f2()方法故意留个错误,我们看下出现bug的情况
![](https://img-my.csdn.net/uploads/201208/14/1344909747_4213.jpg)
![](https://img-my.csdn.net/uploads/201208/14/1344909762_4037.jpg)
本文转载自:http://blog.sina.com.cn/bestfeiyong