开发手册 欢迎您!
软件开发者资料库

TestNG - 执行程序

本章介绍了TestNG中方法的执行过程.它解释了所谓方法的顺序.以下是TestNG测试API方法的执行过程及其示例.

本章介绍了TestNG中方法的执行过程.它解释了所谓方法的顺序.以下是TestNG测试API方法的执行过程及其示例.

C:\中创建java类文件名 TestngAnnotation.java > 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 b> C:\> TestNG_WORKSPACE 执行注释.

                           

使用javac编译测试用例类.

C:\TestNG_WORKSPACE>javac TestngAnnotation.java

现在,运行testng.xml,它将运行在提供的Test Case类中定义的测试用例.

C:\TestNG_WORKSPACE>java org.testng.TestNG testng.xml

验证输出.

in beforeSuitein beforeTestin beforeClassin beforeMethodin test case 1in afterMethodin beforeMethodin test case 2in afterMethodin afterClassin afterTestin afterSuite===============================================SuiteTotal tests run: 2, Failures: 0, Skips: 0===============================================

根据以上输出,执行程序如下 :

  • 首先,beforeSuite()方法只执行一次.

  • 最后,afterSuite()方法只执行一次.

  • 甚至方法beforeTest(),beforeClass(),afterClass()和afterTest()方法也只执行一次.

  • beforeMethod()方法为每个测试用例执行但在执行测试用例之前.

  • afterMethod()方法在执行测试用例后执行每个测试用例.

  • 在beforeMethod()和afterMethod()之间,每个测试用例都会执行.