1. 程式人生 > >TestNG使用excel進行資料驅動程式碼

TestNG使用excel進行資料驅動程式碼

資料驅動測試

自動化功能測試的一個主要好處是能夠快速測試系統上的大量資料。但您必須能夠操作資料集,執行計算,並以最少的工作量快速建立數百個測試迭代和排列。測試自動化框架必須具有與電子表格整合的功能,並提供強大的計算功能。

 

Apache POI(Excel)

市場上大多數商業自動化軟體工具都支援某種資料驅動測試,它允許您使用不同的輸入和驗證值自動執行測試用例多次。由於Selenium Webdriver更像是一個自動化測試框架,而不是一個現成的工具,因此您必須付出一些努力來支援自動化測試中的資料驅動測試。我通常更喜歡使用Microsoft Excel作為儲存我的引數的格式。使用Excel的另一個好處是,您可以輕鬆地將測試資料管理外包給除您自己之外的其他人,可能更好地瞭解需要執行的測試用例以及執行這些測試用例所需的引數。

TestNG資料提供商

當您需要傳遞需要從Java建立的複雜引數或引數(複雜物件,從屬性檔案或資料庫中讀取的物件等)時,在這種情況下,可以使用Dataproviders傳遞引數。資料提供程式是使用@DataProvider註釋的方法。資料提供程式返回一個物件陣列。

讓我們看一下使用Data Providers with Excel資料表的相同登入示例。

怎麼做…

在這裡,我們將按照一個簡單的步驟流程來實現使用TestNg資料提供程式實現Excel。

步驟1:使用TestNG Data Provider建立Login Application的測試用例。

第2步:   建立測試資料表。

第3步:建立從Excel開啟和讀取資料的功能

步驟4:建立一個TestNg測試用例,用於使用Data Provider從Excel接受資料。

步驟5:針對Test Data檔案中的Test Case名稱執行測試。

 

步驟1:使用TestNG Data Provider建立LogIn Application的測試用例

1)按Ctrl + N建立TestNG類'DataProviderTest',在TestNG類別下選擇'Create TestNG Class',在Under Annotations下,選中'DataProvider'並單擊Finish。

2)預設情況下,DataProvider名稱為“dp”,將其更改為“Authentication”。此方法返回物件陣列的陣列。

3)將方法Registration_data()新增到Test類。此方法將兩個字串作為輸入引數。

4)在方法@Test下編寫LogIn Application的指令碼。

測試用例如下所示:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

package automationFramework;

 

import java.util.concurrent.TimeUnit;

 

import org.openqa.selenium.By;

 

import org.openqa.selenium.WebDriver;

 

import org.openqa.selenium.firefox.FirefoxDriver;

 

import org.testng.annotations.DataProvider;

 

import org.testng.annotations.Test;

 

public class DataProviderTest {

 

    private static WebDriver driver;

 

  @DataProvider(name = "Authentication")

 

  public static Object[][] credentials() {

 

        // The number of times data is repeated, test will be executed the same no. of times

 

        // Here it will execute two times

 

        return new Object[][] { { "testuser_1", "[email protected]" }, { "testuser_1", "[email protected]" }};

 

  }

 

  // Here we are calling the Data Provider object with its Name

 

  @Test(dataProvider = "Authentication")

 

  public void test(String sUsername, String sPassword) {

 

      driver = new FirefoxDriver();

 

      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 

      driver.get("http://www.store.demoqa.com");

 

      driver.findElement(By.xpath(".//*[@id='account']/a")).click();

 

      // Argument passed will be used here as String Variable

 

      driver.findElement(By.id("log")).sendKeys(sUsername);

 

      driver.findElement(By.id("pwd")).sendKeys(sPassword);

 

      driver.findElement(By.id("login")).click();

 

      driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

 

      driver.quit();

 

  }

 

}

 

第2步:建立測試資料表

1)建立一個' New Package '檔案並將其命名為' testData' ,右鍵單擊Project並選擇  New  >  Package 。我總是將我的測試資料檔案放在單獨的測試資料資料夾中。

 

2)將 Excel  檔案放在上面建立的包位置中,並將其另存為 TestData.xlsx 。在excel中填寫資料,如下圖所示:

使用Excel的TestNG資料提供程式

 

 

第3步:建立從Excel開啟和讀取資料的功能

我們需要一種方法來開啟這個Excel工作表,並在我們的Selenium測試指令碼中從中讀取資料。為此,我使用Apache POI庫,它允許您使用Java讀取,建立和編輯Microsoft Office文件。我們將用於從Excel工作表中讀取資料的類和方法位於org.apache.poi.hssf.usermodel包中。

要檢視設定Apache POI Excel的分步過程,請訪問Data Driven Framework。

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

package utility;

 

        import java.io.FileInputStream;

 

import java.io.FileNotFoundException;

 

import java.io.FileOutputStream;

 

import java.io.IOException;

 

import org.apache.poi.xssf.usermodel.XSSFCell;

 

import org.apache.poi.xssf.usermodel.XSSFRow;

 

import org.apache.poi.xssf.usermodel.XSSFSheet;

 

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

    public class ExcelUtils {

 

private static XSSFSheet ExcelWSheet;

 

private static XSSFWorkbook ExcelWBook;

 

private static XSSFCell Cell;

 

private static XSSFRow Row;

 

public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {  

 

   String[][] tabArray = null;

 

   try {

 

   FileInputStream ExcelFile = new FileInputStream(FilePath);

 

   // Access the required test data sheet

 

   ExcelWBook = new XSSFWorkbook(ExcelFile);

 

   ExcelWSheet = ExcelWBook.getSheet(SheetName);

 

   int startRow = 1;

 

   int startCol = 1;

 

   int ci,cj;

 

   int totalRows = ExcelWSheet.getLastRowNum();

 

   // you can write a function as well to get Column count

 

   int totalCols = 2;

 

   tabArray=new String[totalRows][totalCols];

 

   ci=0;

 

   for (int i=startRow;i<=totalRows;i++, ci++) {             

 

  cj=0;

 

   for (int j=startCol;j<=totalCols;j++, cj++){

 

   tabArray[ci][cj]=getCellData(i,j);

 

   System.out.println(tabArray[ci][cj]);  

 

}

 

}

 

}

 

catch (FileNotFoundException e){

 

System.out.println("Could not read the Excel sheet");

 

e.printStackTrace();

 

}

 

catch (IOException e){

 

System.out.println("Could not read the Excel sheet");

 

e.printStackTrace();

 

}

 

return(tabArray);

 

}

 

public static String getCellData(int RowNum, int ColNum) throws Exception {

 

try{

 

Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);

 

int dataType = Cell.getCellType();

 

if  (dataType == 3) {

 

return "";

 

}else{

 

String CellData = Cell.getStringCellValue();

 

return CellData;

 

}catch (Exception e){

 

System.out.println(e.getMessage());

 

throw (e);

 

}

 

}

 

}

 

步驟4:建立一個TestNg測試用例,用於使用Data Provider從Excel接受資料

1)按Ctrl + N建立TestNG類'DataProviderWithExcel',在TestNG類別下選擇' Create TestNG Class ',在Under Annotations下,選中' @BeforeMethod ',' @ AfterMethod '和' DataProvider ',然後單擊Finish。

3)將方法Registration_data()新增到Test類。此方法將兩個字串作為輸入引數。

4)現在將測試用例分為三部分:

@BeforeMethod:啟動Firefox並將其指向基本URL

@Test:輸入登入使用者名稱和密碼,列印控制檯訊息並登出

@AfterMethod:關閉Firefox瀏覽器

測試用例如下所示:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

package practiceTestCases;

 

import java.util.concurrent.TimeUnit;

 

import org.openqa.selenium.By;

 

import org.openqa.selenium.WebDriver;

 

import org.openqa.selenium.firefox.FirefoxDriver;

 

import org.testng.annotations.AfterMethod;

 

import org.testng.annotations.BeforeMethod;

 

import org.testng.annotations.Test;

 

import org.testng.annotations.DataProvider;

 

import utility.ExcelUtils;

 

public class DataProviderWithExcel_001 {

 

WebDriver driver;

 

    @BeforeMethod

 

    public void beforeMethod() throws Exception {

 

    driver = new FirefoxDriver();

 

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 

        driver.get("http://www.store.demoqa.com");

 

}

 

@Test(dataProvider="Authentication")

 

    public void Registration_data(String sUserName,String sPassword)throws  Exception{

 

        driver.findElement(By.xpath(".//*[@id='account']/a")).click();

 

        driver.findElement(By.id("log")).sendKeys(sUserName);

 

System.out.println(sUserName);

 

        driver.findElement(By.id("pwd")).sendKeys(sPassword);

 

System.out.println(sPassword);

 

        driver.findElement(By.id("login")).click();

 

        System.out.println(" Login Successfully, now it is the time to Log Off buddy.");

 

        driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

 

}

 

    @DataProvider

 

    public Object[][] Authentication() throws Exception{

 

         Object[][] testObjArray = ExcelUtils.getTableArray("D://ToolsQA//OnlineStore//src//testData//TestData.xlsx","Sheet1");

 

         return (testObjArray);

 

}

 

    @AfterMethod

 

    public void afterMethod() {

 

       driver.close();

 

     }

 

}

 

注意:此LogIn測試將執行兩次,因為資料提供程式Array中有兩個使用者憑據。

步驟5:針對Test Data檔案中的Test Case名稱執行測試

1)這意味著您的測試應僅使用針對測試用例名稱提及的資料執行一次。為此,我們需要調整Excel實用程式類,還需要新增一些函式來獲取當前的測試用例名稱和包含測試用例名稱的行號。

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

package utility;

 

import java.io.FileInputStream;

 

import java.io.FileNotFoundException;

 

import java.io.FileOutputStream;

 

import java.io.IOException;

 

import org.apache.poi.xssf.usermodel.XSSFCell;

 

import org.apache.poi.xssf.usermodel.XSSFRow;

 

import org.apache.poi.xssf.usermodel.XSSFSheet;

 

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

    public class ExcelUtils {

 

private static XSSFSheet ExcelWSheet;

 

private static XSSFWorkbook ExcelWBook;

 

private static XSSFCell Cell;

 

private static XSSFRow Row;

 

//This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method

 

public static void setExcelFile(String Path,String SheetName) throws Exception {

 

   try {

 

// Open the Excel file

 

FileInputStream ExcelFile = new FileInputStream(Path);

 

// Access the required test data sheet

 

ExcelWBook = new XSSFWorkbook(ExcelFile);

 

ExcelWSheet = ExcelWBook.getSheet(SheetName);

 

} catch (Exception e){

 

throw (e);

 

}

 

}

 

public static Object[][] getTableArray(String FilePath, String SheetName, int iTestCaseRow)    throws Exception

 

{  

 

   String[][] tabArray = null;

 

   try{

 

   FileInputStream ExcelFile = new FileInputStream(FilePath);

 

   // Access the required test data sheet

 

   ExcelWBook = new XSSFWorkbook(ExcelFile);

 

   ExcelWSheet = ExcelWBook.getSheet(SheetName);

 

   int startCol = 1;

 

   int ci=0,cj=0;

 

   int totalRows = 1;

 

   int totalCols = 2;

 

   tabArray=new String[totalRows][totalCols];

 

   for (int j=startCol;j<=totalCols;j++, cj++)

 

   {

 

   tabA