TestNG - 執行步驟



本章節解釋 TestNG 中方法的執行步驟。它解釋了所呼叫方法的順序。以下是 TestNG 測試 API 方法的執行步驟,並附有示例。

/work/testng/src中建立名為TestngAnnotation.java 的 Java 類檔案來測試註解。

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");
   }

}

接下來,讓我們在/work/testng/src中建立檔案testng.xml 來執行註解。

<?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 編譯測試案例類。

/work/testng/src$ javac TestngAnnotation.java

現在,執行 testng.xml,這將執行在提供的測試案例類中定義的測試案例。

/work/testng/src$ 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
===============================================

根據上述輸出,執行步驟如下 -

  • 首先,beforeSuite() 方法只執行一次。

  • 最後,afterSuite() 方法只執行一次。

  • 即使是 beforeTest()、BeforeClass()、AfterClass() 和 afterTest() 方法只執行一次。

  • beforeMethod() 方法針對每個測試案例執行,但在執行測試案例之前執行。

  • afterMethod() 方法針對每個測試案例執行,但在執行測試案例之後執行。

  • 每個測試案例在 beforeMethod() 和 afterMethod() 之間執行。

廣告
© . All rights reserved.