Excel/csv Data Driven+Selenium+Maven

跟着Rahul学到Framework,于是开始基于公司的项目搭建自己的Framework。

Data Driven部分对@Data Provider已经可以熟练运用,今天自己试了一下excel,后面再抽时间去搞Mysql Database。

在网上搜了一些Excel Data Driven的demo,不是太简单就是太难,Rahul的太简单都没有适合自己的,重新去看了下虫师的 6.3.3 读取csv 文件 这一章节, 很简单清晰,然后搜了一下excel和csv的区别,其实也可以通用,上一家樱桃儿公司我们做Integration用的还都是excel convert to csv呢。于是打算开始码csv,至少以后问起来,这块儿不是盲点。

目的:针对项目,新建factory配置,能够通过页面元素定位到box或者dropdown,然后从excel表里获取数据,新建成功,继续新建factory。可自动化实现从excel中读取factory配置所需要的参数,循环建立多个factory。

上代码:

Base.java

package resources;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
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.csvreader.CsvReader;



public class Base{
	
	public static WebDriver driver;
	public static Properties prop;
	public static Logger logger = LogManager.getLogger(Base.class.getName());
	public static FileInputStream fis;
	
	static {
		prop = new Properties();
		try {
			fis = new FileInputStream("E:\\selenium\\mavenRepo\\MavenProject\\src\\main\\java\\resources\\data.properties");
	        prop.load(fis);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public WebDriver initDriverBase() throws IOException{
		prop = new Properties();
		FileInputStream fis = new FileInputStream("E:\\selenium\\mavenRepo\\MavenProject\\src\\main\\java\\resources\\data.properties");
        prop.load(fis);
        
        String browserName = prop.getProperty("browser");
        System.out.println("browser name :" + browserName);
        
        if(browserName.contains("chrome")){
    		System.setProperty("webdriver.chrome.driver", System.getProperties().getProperty("user.dir")+"\\chromedriver.exe");  
    		driver = new ChromeDriver();
        }
        else if(browserName.contains("firefox")){
        	driver = new FirefoxDriver();
        }
        else{
        	driver = new InternetExplorerDriver();
        }
        
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
        return driver;
	}
	
	public void getScreenShotBase(String result) throws IOException{
		File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(src, new File("E://selenium//mavenRepo//ScreenShot//" + result + "screenshot.png"));
		
	}
	
	public ArrayList<String[]> readCSVFile(String filePath) throws IOException{
		// ArrayList 用来保存数据
		ArrayList<String[]> csvList = new ArrayList<String[]>();
		// 一般用这编码读就可以了
		CsvReader reader = new CsvReader(filePath, ',', Charset.forName("SJIS"));
		// 跳过表头,如果需要表头,不要写这句
		reader.readHeaders();
		
		while(reader.readRecord()){  // 逐行读入除表头的数据
			csvList.add(reader.getValues());
		}
		
		reader.close();
		
		for(int row=0; row<csvList.size(); row++){
			System.out.println(csvList.get(row)[0]);
			System.out.println(csvList.get(row)[1]);
			System.out.println(csvList.get(row)[2]);
			System.out.println(csvList.get(row)[3]);
			System.out.println(csvList.get(row)[4]);
			System.out.println(csvList.get(row)[5]);
			System.out.println(csvList.get(row)[6]);
			System.out.println(csvList.get(row)[7]);
			System.out.println(csvList.get(row)[8]);
			System.out.println("---------------------------");
		}	
		
		return csvList;
	}
}

ElementGCPI.java

package pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class ElementGCPI {
	
	public static WebElement loginText(WebDriver driver){
		return driver.findElement(By.xpath("//p[@class='container-section-p']"));
	}
	
	public static WebElement usernameBox(WebDriver driver){
		img[contains(@alt,'g1')]
		return driver.findElement(By.xpath("//input[contains(@class,'container-section-inputOne container-section-input')]"));
	}
	
	public static WebElement passwordBox(WebDriver driver){
		return driver.findElement(By.xpath("//input[contains(@class,'container-section-inputTwo container-section-input')]"));
	}
	
	public static WebElement loginButton(WebDriver driver){
		return driver.findElement(By.xpath("//div[@ng-click='fn_login()']"));
	}
	
	public static WebElement alertText(WebDriver driver){
		return driver.findElement(By.xpath("//li[@ng-bind='alertTxt']"));
	}
	
	public static WebElement logoutButton(WebDriver driver){
		return driver.findElement(By.xpath("//span[@title='退出当前账号']"));
	}
	
	public static WebElement basicConfigButton(WebDriver driver){
		return driver.findElement(By.xpath("//div[@id='id_basicManager_div']"));
	}
	
	public static WebElement factoryConfigButton(WebDriver driver){
		return driver.findElement(By.xpath("//li[@id='plantFactoryId']"));
	}
	
	public static WebElement factoryCreateButton(WebDriver driver){
		return driver.findElement(By.xpath("//*[@id='id_addNew']"));
	}
	
	public static WebElement factoryCreateNameBox(WebDriver driver){
		return driver.findElement(By.xpath("//*[@id='form-field-1']"));
	}
	
	public static void factoryTypeDropdown(WebDriver driver, int index){
		Select s = new Select(driver.findElement(By.xpath("//div[@class='widget-main']/div[1]/div[2]/select")));
		s.selectByIndex(index);

	}
	
	public static void factoryZoneDropdown(WebDriver driver, int index){
		Select s = new Select(driver.findElement(By.xpath("//div[@class='widget-main']/div[2]/select")));
		s.selectByIndex(index);

	}
	
	public static WebElement factoryLeftXBox(WebDriver driver){
		return driver.findElement(By.xpath("//*[@id='form-field-171']"));
	}
	
	public static WebElement factoryLeftYBox(WebDriver driver){
		return driver.findElement(By.xpath("//*[@id='form-field-11']"));
	}
	
	public static WebElement factoryWidthBox(WebDriver driver){
		return driver.findElement(By.xpath("//*[@id='form-field-1171']"));
	}
	
	public static WebElement factoryHeightBox(WebDriver driver){
		return driver.findElement(By.xpath("//*[@id='form-field-1111']"));
	}
	
	public static WebElement factorySampleTimeBox(WebDriver driver){
		return driver.findElement(By.xpath("//div[@id='allow_drag_move_id_addFactory']/div/div[5]/div/input"));
	}
	
	public static void factoryUnitDropdown(WebDriver driver, int index){
		Select s = new Select(driver.findElement(By.xpath("//div[@class='widget-main']/div[5]/div[2]/select")));
		s.selectByIndex(index);
	}
	
	
}

测试类:

FactoryConfigTest.java

package gcpi;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import pageAction.PageAction;
import pageObjects.ElementGCPI;
import resources.Base;

public class FactoryConfigTest extends Base{

	@BeforeClass
	public void setUp() throws Exception{
		// navigate to url
		driver = initDriverBase();
		driver.get(prop.getProperty("url"));
		// login
		PageAction.login(driver, prop.getProperty("username"), prop.getProperty("password"));
		
		Thread.sleep(2000);
		driver.manage().window().maximize();
		ElementGCPI.basicConfigButton(driver).click();
		Thread.sleep(2000);
		ElementGCPI.factoryConfigButton(driver).click();
		Thread.sleep(2000);
	}
	
	@Test
	public void createFactoryConfigTest() throws IOException, InterruptedException{
		
		ArrayList<String[]> csvList = readCSVFile(prop.getProperty("csvfilePath"));
		
		for(int row=0; row<csvList.size(); row++){
			
			ElementGCPI.factoryCreateButton(driver).click();
			
			// Read CSV file 
			// Refer to 虫师    “6.3.3 读取csv 文件”
			ElementGCPI.factoryCreateNameBox(driver).sendKeys(csvList.get(row)[0]);
			// String -> int : int i = Integer.parseInt(str)
			ElementGCPI.factoryTypeDropdown(driver, Integer.parseInt(csvList.get(row)[1]));
			ElementGCPI.factoryZoneDropdown(driver, Integer.parseInt(csvList.get(row)[2]));
			ElementGCPI.factoryLeftXBox(driver).sendKeys(csvList.get(row)[3]);
			ElementGCPI.factoryLeftYBox(driver).sendKeys(csvList.get(row)[4]);
			ElementGCPI.factoryWidthBox(driver).sendKeys(csvList.get(row)[5]);
			ElementGCPI.factoryHeightBox(driver).sendKeys(csvList.get(row)[6]);
			ElementGCPI.factorySampleTimeBox(driver).sendKeys(csvList.get(row)[7]);
			ElementGCPI.factoryUnitDropdown(driver, Integer.parseInt(csvList.get(row)[8]));
			ElementGCPI.factoryCreateConfirmButton(driver).click();
			Thread.sleep(2000);
			ElementGCPI.AlertButton(driver).click();
			Thread.sleep(2000);
			logger.info("------row:"+ row + "---------");

			int count = driver.findElements(By.xpath("html/body/div[5]/div/div/div/div/div[2]/table/tbody/tr")).size();
			String element = "";
			for(int i=0; i<count-1; i++){
				element = driver.findElements(By.xpath("html/body/div[5]/div/div/div/div/div[2]/table/tbody/tr/td[2]")).get(i).getText();
				logger.info("-------element---" + element);
				logger.info("-----csvList.get(row)[1]:" + csvList.get(row)[0]);
				if(element.equals(csvList.get(row)[0])){
					break;
				}
			}
				
			String expectedText = csvList.get(row)[0];
			Assert.assertEquals(element, expectedText);
		}

	}
	
	@AfterClass
	public void tearDown(){
		driver.quit();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,作为AI语言模型,我无法为您创建完整的项目。但是,我可以为您提供创建SSM Maven Web项目的步骤,您可以根据这些步骤自己创建项目。 步骤如下: 1. 在Eclipse或IntelliJ IDEA中,创建一个Maven项目。 2. 在pom.xml中添加以下依赖项: ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> </dependencies> ``` 3. 创建一个Spring配置文件,例如applicationContext.xml,添加以下内容: ``` <context:component-scan base-package="com.example"></context:component-scan> ``` 4. 创建一个MyBatis配置文件,例如mybatis-config.xml,添加以下内容: ``` <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <package name="com.example.model"/> </typeAliases> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration> ``` 5. 创建一个数据库连接池配置文件,例如db.properties,添加以下内容: ``` jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=root ``` 6. 创建一个Spring MVC配置文件,例如spring-mvc.xml,添加以下内容: ``` <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> ``` 7. 创建一个控制器类,例如UserController.java,添加以下内容: ``` @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/list") public ModelAndView list() { List<User> userList = userService.getAllUsers(); ModelAndView modelAndView = new ModelAndView("user/list"); modelAndView.addObject("userList", userList); return modelAndView; } } ``` 8. 创建一个服务类,例如UserService.java,添加以下内容: ``` public interface UserService { List<User> getAllUsers(); } ``` 9. 创建一个服务实现类,例如UserServiceImpl.java,添加以下内容: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; public List<User> getAllUsers() { return userMapper.getAllUsers(); } } ``` 10. 创建一个数据访问接口,例如UserMapper.java,添加以下内容: ``` public interface UserMapper { List<User> getAllUsers(); } ``` 11. 创建一个数据访问接口实现类,例如UserMapperImpl.java,添加以下内容: ``` @Repository public class UserMapperImpl implements UserMapper { @Autowired private SqlSessionFactory sqlSessionFactory; public List<User> getAllUsers() { SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> userList = sqlSession.selectList("com.example.mapper.UserMapper.getAllUsers"); sqlSession.close(); return userList; } } ``` 12. 创建一个JSP页面,例如list.jsp,添加以下内容: ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>User List</title> </head> <body> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <c:forEach items="${userList}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> </tr> </c:forEach> </tbody> </table> </body> </html> ``` 13. 部署并启动Web应用程序,浏览器中输入"http://localhost:8080/项目名/user/list",即可查看用户列表页面。 希望这些步骤能够帮助您创建SSM Maven Web项目。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值