我是靠谱客的博主 背后大米,这篇文章主要介绍【selenium】利用excel来实现关键字驱动-Java,现在分享给大家,希望可以做个参考。

参考地址:https://my.oschina.net/hellotest/blog/531932#comment-list

一、新建项目



二、导入包


三、例子-excel

    以CSDN的登录为例,首先我们可以分解登录的步骤,写入excel,如下:



四、编码

1、首先需要写一个可以读写excel的方法,我电脑上装的是excel7,xlsx格式,用到XSS系列的方法,代码如下:

复制代码
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
package com.model.lib; 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; /** * 操作excel类 * @author Admin * */ public class ExcelUtil { public static XSSFSheet excelSheet; public static XSSFWorkbook excelBook; public static XSSFRow row; public static XSSFCell cell; /** * 加载excel * @param path excel文件路径 */ public static void setExcelFile(String path) { FileInputStream excelFile; try { excelFile = new FileInputStream(path); excelBook = new XSSFWorkbook(excelFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取excel中对应单元格的值 * @param rownum 行(从0开始) * @param cellnum 列(从0开始) * @param sheetName sheet名 * @return */ public static String getCellData(int rownum,int cellnum,String sheetName) { excelSheet = excelBook.getSheet(sheetName); cell = excelSheet.getRow(rownum).getCell(cellnum); String cellData = cell.getStringCellValue(); return cellData; } /** * 将测试结果写入excel * @param result 测试结果 * @param rownum 行(从0开始) * @param cellnum 列(从0开始) * @param path excel文件路径 * @param sheetName sheet名 */ public static void setCellData(String result,int rownum,int cellnum,String path,String sheetName) { try { excelSheet = excelBook.getSheet(sheetName); row = excelSheet.getRow(rownum); cell = row.getCell(cellnum, row.RETURN_BLANK_AS_NULL); if (cell == null) { cell = row.createCell(cellnum); cell.setCellValue(result); } else { cell.setCellValue(result); } FileOutputStream fileOut = new FileOutputStream(path); excelBook.write(fileOut); fileOut.flush(); fileOut.close(); excelBook = new XSSFWorkbook(new FileInputStream(path)); }catch (Exception ex) { ex.printStackTrace(); } } /** * 获取excel的sheet的最后一行 * @param sheetName * @return */ public static int getLastRownum(String sheetName) { int row = 0; try { excelSheet = excelBook.getSheet(sheetName); row = excelSheet.getLastRowNum(); } catch (Exception ex) { ex.printStackTrace(); } return row; } }

2、登录步骤需要用到的方法,对应login的测试步骤

复制代码
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
package com.model.keyword; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import com.model.lib.DataStore; /** * 关键字步骤对应的方法 * @author Admin * */ public class LoginKeyword { public static WebDriver driver; /** * 打开浏览器并最大化窗口 */ public static void OpenBrowser() { System.setProperty(DataStore.key, DataStore.driverurl); if (DataStore.startExplore.equals("firefox")) { driver = new FirefoxDriver(); } else if (DataStore.startExplore.equals("chorme")){ driver = new ChromeDriver(); } else { driver = new InternetExplorerDriver(); } driver.manage().window().maximize(); } /** * 打开网址 */ public static void Navigate() { driver.get(DataStore.loginUrl); } /** * 输入用户名 * @param pe 页面元素 * @param value 输入的值 */ public static void InputUsername(String pe,String value) { driver.findElement(By.id(pe)).clear(); driver.findElement(By.id(pe)).sendKeys(value); } /** * 输入密码 * @param pe 页面元素 * @param value 输入的值 */ public static void InputPassword(String pe,String value) { driver.findElement(By.id(pe)).clear(); driver.findElement(By.id(pe)).sendKeys(value); } /** * 点击登录 * @param pe 页面元素 */ public static void ClickLogin(String pe) { driver.findElement(By.xpath(pe)).click(); } /** * 关闭浏览器 */ public static void CloseBrowser() { driver.quit(); } }
3、根据excel将需要的参数定义出来(Config.properties)
复制代码
1
2
3
4
5
# 浏览器驱动路径 startExplore = firefox key = webdriver.firefox.bin driverurl = C:/Program Files/Mozilla Firefox/firefox.exe

4、读取参数文件

复制代码
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
package com.model.lib; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; /** * 读取配置文件的内容 * @author Admin * */ public class PropertiesFile { public static String read(String key) { Properties pps = new Properties(); InputStream in = null; try { // 读取config文件 File file = new File("F:/selenium/workplace/CsdnKeywordModel/assets/Config.properties"); in = new BufferedInputStream(new FileInputStream(file)); pps.load(in);// 加载属性列表 if (pps.containsKey(key)) { String value = pps.getProperty(key); return value; // 返回读取的内容 } else { System.out.println("没有读取到"+key); return null; } } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { PropertiesFile pf = new PropertiesFile(); String ss = pf.read("user"); System.out.println(ss); } }

5、读取的数据

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.model.lib; /** * 读取的数据 * @author Admin * */ public class DataStore { // 驱动路径 public static String driverurl = PropertiesFile.read("driverurl"); public static String key = PropertiesFile.read("key"); public static String startExplore = PropertiesFile.read("startExplore"); public static void main(String[] args) { System.out.println(driverurl); } }

6、定义登录时需要用到的常量

复制代码
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
package com.model.keyword.contant; /** * 登录关键字需要的常量 * @author Admin * */ public class LoginContant { // 登录URL public static String loginUrl = "https://passport.csdn.net/account/login"; // 读取文件的文件夹路径 public static String TextPath = "F:/selenium/workplace/CsdnKeywordModel/assets/"; // 读取的文件名 public static String fileName = "pageElements.xlsx"; // 读取的文件的sheet public static String suiteSheet = "Suite"; public static String caseSheet = "login"; // 用例执行的结果定义 public static String pass = "PASS"; public static String fail = "FAIL"; //suite需要用到的参数(对应值所在的列) public static int suiteTestIdCol = 0; public static int suiteRunmodeCol = 2; public static int suiteResultCol = 3; // case需要用到的参数(对应值所在的列) public static int caseTestIdCol = 0; public static int caseKeywordCol = 1; public static int casePageElementCol = 3; public static int casePageValueCol = 4; public static int caseResultCol = 5; }
7、利用反射执行关键字类中的方法(这里注意,如果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
package com.model.lib; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.model.keyword.contant.LoginContant; /** * 将excel的处理逻辑和关键字逻辑相分离 * @author Admin * */ public class CommonEngine { /** * 执行关键字中的方法 * @param keyword 关键字方法名称 * @param actionKeywords 关键字类 * @param pe 页面元素 * @param value 需要用到的值 * @param rownum 哪一行 * @param sresult 执行结果 */ public static void Action(String keyword,Object actionKeywords,String pe,String value,int rownum,boolean sresult) { // 根据反射机制获取关键字类中的方法 Method[] method = actionKeywords.getClass().getMethods(); for (int i = 0; i < method.length; i++) {// 循环遍历关键字类中的方法 if (method[i].getName().trim().equals(keyword)) { // 如果关键字类中的方法和excel关键字的方法一致 try { if (pe.equals("无") && value.equals("无")) { method[i].invoke(actionKeywords); } else if (!(pe.equals("无")) && value.equals("无")) { method[i].invoke(actionKeywords, pe); } else if (pe.equals("无") && !(value.equals("无"))) { method[i].invoke(actionKeywords, value); } else { method[i].invoke(actionKeywords, pe, value); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } break; } } } }
8、编写登录的脚本
复制代码
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
package com.model.test; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Test; import com.model.keyword.LoginKeyword; import com.model.keyword.contant.LoginContant; import com.model.lib.CommonEngine; import com.model.lib.ExcelUtil; public class Login { public static Logger logger = Logger.getLogger(Login.class.getName()); public static LoginKeyword loginkeyword; public static String keyword; public static String pe; public static String value; public static boolean result; public Login () { loginkeyword = new LoginKeyword(); } @Test public void test() { ExcelUtil.setExcelFile(LoginContant.TextPath+LoginContant.fileName);// 加载登录文件 new Login(); result = true; //循环读取suitSheet里面的值,找出运行的场景 for (int j = 1;j<=ExcelUtil.getLastRownum(LoginContant.suiteSheet);j++) { // 读取suitesheet里面的runmode字段,如果为yes则执行该用例,No则不执行 String runMode = ExcelUtil.getCellData(j, LoginContant.suiteRunmodeCol, LoginContant.suiteSheet); // 读取suitesheet里面的testsuiteID字段 String suiteTestid = ExcelUtil.getCellData(j, LoginContant.suiteTestIdCol, LoginContant.suiteSheet); //int srownum; if (runMode.equals("YES")) { logger.log(Level.INFO, "开始执行第"+j+"条"); // 循环遍历loginsheet里面的值,找出运行的步骤 for (int srownum = 1;srownum<=ExcelUtil.getLastRownum(LoginContant.caseSheet);srownum++) { // 获取loginsheet里面的测试用例序号 String loginTestid = ExcelUtil.getCellData(srownum, LoginContant.caseTestIdCol, LoginContant.caseSheet); if (loginTestid.trim().equals(suiteTestid)) { // 如果loginsheet里面的测试用例序号和suitesheet里面的用例序号一致 // 获取loginsheet里面的测试步骤序号(和loginkeyword里面的方法对应) keyword = ExcelUtil.getCellData(srownum, LoginContant.caseKeywordCol, LoginContant.caseSheet); // 获取loginsheet里面的页面元素(id,xpath路径等) pe = ExcelUtil.getCellData(srownum, LoginContant.casePageElementCol, LoginContant.caseSheet); // 获取loginsheet里面的值(需要输入或者对比的值) value = ExcelUtil.getCellData(srownum, LoginContant.casePageValueCol, LoginContant.caseSheet); CommonEngine.Action(keyword, loginkeyword, pe, value, srownum, result); if (result == true) {// 将结果写入loginsheet ExcelUtil.setCellData(LoginContant.pass, srownum, LoginContant.caseResultCol, LoginContant.TextPath+LoginContant.fileName, LoginContant.caseSheet); } else {// 将结果写入loginsheet ExcelUtil.setCellData(LoginContant.fail, srownum, LoginContant.caseResultCol, LoginContant.TextPath+LoginContant.fileName, LoginContant.caseSheet); } if (result == false) {// 将结果写入suitesheet ExcelUtil.setCellData(LoginContant.fail, j, LoginContant.suiteResultCol, LoginContant.TextPath+LoginContant.fileName, LoginContant.suiteSheet); logger.log(Level.INFO, "第"+j+"条用例执行完成"); } } } if (result == true) {// 将结果写入suitesheet ExcelUtil.setCellData(LoginContant.pass, j, LoginContant.suiteResultCol, LoginContant.TextPath+LoginContant.fileName, LoginContant.suiteSheet); logger.log(Level.INFO, "第"+j+"条用例执行完成"); } } else { logger.log(Level.INFO, "没有要执行的用例"); break; } } } }

9、在套件中执行

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.model.mysuite; import com.model.report.HtmlReport; import com.model.test.Login; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; public class MySutieMain { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new JUnit4TestAdapter(Login.class)); //登录 //suite.addTest(new JUnit4TestAdapter(HomePageAutoTest.class)); //首页 return suite; } public static void main(String args[]) { HtmlReport hr=new HtmlReport(); hr.createLog("F:\selenium\report\jdhuiTestlog.html"); TestRunner.run(suite()); hr.closeLog(); } }

最后

以上就是背后大米最近收集整理的关于【selenium】利用excel来实现关键字驱动-Java的全部内容,更多相关【selenium】利用excel来实现关键字驱动-Java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部