如何在TestNG中將變數從BeforeTest傳遞到Test註解?
一個TestNG類可以包含各種TestNG方法,例如@BeforeTest,@AfterTest, @BeforeSuite, @BeforeClass, @BeforeMethod, @test等。在許多情況下,我們需要將一些變數從這些方法傳遞到主要的@Test方法。由於這些方法都不支援return型別,所以傳遞變數的最佳方法是使用類/例項變數,而不是區域性變數。
類/例項變數的作用域在整個類中。因此,在@BeforeTest或@BeforeMethod中設定的任何值都可以在@Test方法中使用。
在本文中,我們將學習如何在TestNG中將變數從@BeforeTest傳遞到@Test註解。
解決此問題的方法/演算法
步驟1 - 建立一個TestNG類NewTestngClass並宣告一個名為employeeName的變數。
步驟2 - 在@BeforeTest中寫入以下程式碼:
public void name() {
employeeName = "Ashish";
System.out.println("employeeName is: "+employeeName);
}步驟3 - 在NewTestngClass類中編寫一個@Test方法,並使用程式碼中描述的變數employeeName。
步驟4 - 現在建立如下所示的testNG.xml來執行TestNG類。
步驟5 - 最後,執行testNG.xml或直接在IDE中執行TestNG類,或者使用命令列編譯並執行它。
示例
以下是常用TestNG類NewTestngClass的程式碼:
src/ NewTestngClass.java
import org.testng.annotations.*;
public class NewTestngClass {
String employeeName;
// test case 1
@Test()
public void testCase1() throws InterruptedException {
System.out.println("in test case 1 of NewTestngClass");
String employeeFullName = employeeName + " Anand";
System.out.println("employeeFullName is: "+employeeFullName);
}
@BeforeTest
public void name() {
employeeName = "Ashish";
System.out.println("employeeName is: "+employeeName);
}
}testng.xml
這是一個配置檔案,用於組織和執行TestNG測試用例。當只需要執行有限的測試而不是完整的套件時,它非常方便。
<?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 = "NewTestngClass"/>
</classes>
</test>
</suite>輸出
employeeName is: Ashish in test case 1 of NewTestngClass employeeFullName is: Ashish Anand =============================================== Suite1 Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP