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", "Test@123" }, { "testuser_1", "Test@123" }};

 

  }

 

  // 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中填写数据,如下图所示:

 

 

第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++)

 

   {

 

   tabArray[ci][cj]=getCellData(iTestCaseRow,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);

 

}

 

//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num

 

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

 

   try{

 

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

 

  String CellData = Cell.getStringCellValue();

 

  return CellData;

 

  }catch (Exception e){

 

return"";

 

}

 

}

 

public static String getTestCaseName(String sTestCase)throws Exception{

 

String value = sTestCase;

 

try{

 

int posi = value.indexOf("@");

 

value = value.substring(0, posi);

 

posi = value.lastIndexOf(".");

 

value = value.substring(posi + 1);

 

return value;

 

}catch (Exception e){

 

throw (e);

 

}

 

}

 

public static int getRowContains(String sTestCaseName, int colNum) throws Exception{

 

int i;

 

try {

 

int rowCount = ExcelUtils.getRowUsed();

 

for ( i=0 ; i<rowCount; i++){

 

if  (ExcelUtils.getCellData(i,colNum).equalsIgnoreCase(sTestCaseName)){

 

break;

 

}

 

}

 

return i;

 

}catch (Exception e){

 

throw(e);

 

}

 

}

 

public static int getRowUsed() throws Exception {

 

try{

 

int RowCount = ExcelWSheet.getLastRowNum();

 

return RowCount;

 

}catch (Exception e){

 

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

 

throw (e);

 

}

 

}

 

}

 

最终测试案例

1)获取测试用例名称。

2)使用测试用例名称,获取测试的Excel工作表的行号。

3)从获取的测试行的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

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.Test;

 

import org.testng.annotations.BeforeMethod;

 

import org.testng.annotations.AfterMethod;

 

import org.testng.annotations.DataProvider;

 

import utility.ExcelUtils;

 

public class DataProviderWithExcel_002 {

 

private String sTestCaseName;

 

private int iTestCaseRow;

 

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 f(String sUserName, String sPassword) {

 

    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();

 

  }

 

  @AfterMethod

 

  public void afterMethod() {

 

   driver.close();

 

  }

 

  @DataProvider

 

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

 

    // Setting up the Test Data Excel file

 

ExcelUtils.setExcelFile("D://ToolsQA//OnlineStore//src//testData//TestData.xlsx","Sheet1");

 

sTestCaseName = this.toString();

 

   // From above method we get long test case name including package and class name etc.

 

   // The below method will refine your test case name, exactly the name use have used

 

   sTestCaseName = ExcelUtils.getTestCaseName(this.toString());

 

    // Fetching the Test Case row number from the Test Data Sheet

 

    // Getting the Test Case name to get the TestCase row from the Test Data Excel sheet

 

iTestCaseRow = ExcelUtils.getRowContains(sTestCaseName,0);

 

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

 

     return (testObjArray);

 

}

 

}

注意: 这只会针对当前的案例数据执行一次测试。

你可能感兴趣的:(TestNG)