http://www.yiibai.com/html/testng/2013/0914296.html
本教程介绍了TestNG中执行程序的方法,这意味着该方法被称为第一和一个接着。下面是执行程序的TestNG测试API的方法的例子。
创建一个Java类文件名TestngAnnotation.java在C:\>TestNG_WORKSPACE测试注解。
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;
public class TestngAnnotation {
// test case 1
@Test
public void testCase1() {
System.out.println("in test case 1");
}
// test case 2
@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");
}
}
接下来,让我们创建的文件 testng.xml 在 C:\ > TestNG_WORKSPACE 执行注解。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1">
<test name="test1">
<classes>
<class name="TestngAnnotation"/>
</classes>
</test>
</suite>
编译使用javac测试用例类。
C:\TestNG_WORKSPACE>javac TestngAnnotation.java
现在运行testng.xml,将运行提供的测试用例类中定义的测试用例。
C:\TestNG_WORKSPACE>java org.testng.TestNG testng.xml
验证输出。
in beforeSuite in beforeTest in beforeClass in beforeMethod in test case 1 in afterMethod in beforeMethod in test case 2 in afterMethod in afterClass in afterTest in afterSuite =============================================== Suite Total tests run: 2, Failures: 0, Skips: 0 ===============================================
见上面的输出,TestNG是执行过程如下:
-
首先所有beforeSuite()方法只执行一次。
-
最后,afterSuite的()方法只执行一次。
-
即使方法 beforeTest(), beforeClass(), afterClass() 和afterTest() 方法只执行一次。
-
beforeMethod()方法执行每个测试用例,但在此之前执行的测试用例。
-
afterMethod()方法执行每个测试用例,但测试用例执行后。
-
In between beforeMethod() and afterMethod() each test case executes.