switch window

² 得到弹出的新窗口

import java.util.Iterator;

import java.util.Set;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class Test_popup {

public static void main(String[] args) {

String url = "file:///D:/selenium/html/popup.html";

//打开chrome

WebDriver dr = new ChromeDriver();

dr.get(url);

dr.findElement(By.id("bd")).click();

1. //得到当前窗口的句柄

String currentWindow = dr.getWindowHandle();

2. //存放主页面句柄

String preWindowString=currentWindow;

3. /*得到所有窗口的句柄,存放在Set集合中。

<string>表示set中的键值对都是String类型的

Set<String> handles = dr.getWindowHandles();

4. //获得Set集合的迭代器

Iterator<String> it = handles.iterator();

5. //通过排除当前句柄的方法来得到新开窗口的句柄

while(it.hasNext()){

if(currentWindow == it.next()) continue;

WebDriver window = dr.switchTo().window(it.next());

}

6. //对于当前页面进行操作

System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());

dr.close();//关闭当前页面

7. //返回主页面

WebDriver window=driver.switchTo().window(preWindowString);

8. //对主页面进行操作

System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());

//dr.quit();//关闭全部页面

}

}

² 框架

//首先获得父窗口

driver.switchTo().frame("left");

//取得iframe元素

WebElement weiboIframe = driver.findElement(By.tagName("iframe"));

//获得iframe窗口

driver.switchTo().frame(weiboIframe);

//返回父框架

driver.switchTo().defaultContent();

//得到所有的frame元素

List<WebElement> frames =

driver.findElements(By.tagName("frame"));

//通过页面的内容得到所需的框架 , 没有匹配的时需要回到最初的页面

for (int i = 0; i < frames.size(); i++) {

driver.switchTo().frame(i);

if (driver.getPageSource().contains("middle")) {

break;

}else {

driver.switchTo().defaultContent();

² build().perform()

首先创建一个Actions的实例,再调用相应的事件方法,然后调用build()方法,建立这么一组操作方法链,最后调用perform()来执行。

Actions builder = new Actions(driver);

builder.doubleClick(message).build().perform();

² 显式等待

//设置等待时间10秒

WebDriverWait wait = new WebDriverWait(driver, 10);

//等待直到符合元素文本内容出现。

wait.until(ExpectedConditions.textToBePresentInElement

(By.id("pageContent")));

WebDriverWait每500毫秒调用一次ExpectedCondition直到正确的返回值。

//创建一个新的ExpecctedCondition接口,就必须实现apply方法

WebElement message = wait.until (new ExpectedCondition<WebElement>(){

public WebElement apply(WebDriver d){

return d.findElement(By.cssSelector("#myDiv p")),”123”;}

}

);

自定义的等待可以通过执行一段JavaScript代码并检查返回值来完成。

wait.until(new ExpectedCondition<Boolean>() {

public Boolean apply(WebDriver d) {

JavascriptExecutor js = (JavascriptExecutor) d;

return (Boolean)js.executeScript("return jQuery.active == 0");}

}

);

WebDriverWait wait=new WebDriverWait(driver,30);

wait.until(new ExpectedCondition<Boolean>(){

public Boolean apply(WebDriver d){

JavascriptExecutor js=(JavascriptExecutor) d;

return (Boolean) js.executeScript("if($('#captcha').val().length==4) return true;else return false");

}

});

弹层框

//取alert窗口

Alert alertBox = driver.switchTo().alert();

alertBox.accept(); 警告框

//验证alert窗口里的文字 assertEquals("Hello World",alertBox.getText());

点击确定按钮

点击取消按钮

输入框

getConfirmBox().accept();

getConfirmBox().dismiss();

promptAlert.sendKeys("hello")

数据驱动

import java.util.*;

import org.junit.*;

import org.junit.runner.RunWith;

import org.junit.runners.*;

import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)

public class simpleDDT {

private static WebDriver driver;

private String height;

private String weight;

private String bmi;

private String bmiCategory; //定义待测试类、和变量

@Parameters//定义测试数据集合

public static Collection testData() {

return Arrays.asList(new Object[][]{

{"160","45","17.6","Underweight"},

{"168","70","24.8","Normal"},

});

}

//simpleDDT的构造函数,用来对定义的参数初始化

public simpleDDT(String height,String weight,String bmi,String bmiCategory) {

this.height = height;

this.weight = weight;

this.bmi = bmi;

this.bmiCategory = bmiCategory;

}

@Test

public void testBMICalculator() {

driver = new FirefoxDriver();

driver.get("d:Calculator.html");

//输入身高

WebElement heightField = driver.findElement(By.name("heightCMS"));

heightField.sendKeys(height);

assertEquals(bmi, bmiLabel.getAttribute("value"));

 

}

}

 

u //参数化 csv

@Parameters

public static Collection<String[]> testData() {

return getTestData("d:demodata.csv");

}

//读取CSV中的文件

public static Collection<String[]> getTestData(String path){

List<String[]> records = new ArrayList<String[]>();

String row;

try {

BufferedReader br = new BufferedReader(new FileReader(path));

while ((row = br.readLine())!=null) {

String fields[] = row.split(",");

records.add(fields);

}

br.close();

} catch (Exception e) {

e.printStackTrace();

}

return records;

}

当测试执行的时候,testData()方法调用getTestData()方法来获得测试的数据,通过逗号将字符串分割成数组再添加到集合当中。每一行的数据都会通过构造函数来进行初始化赋值。

 

u //参数化 Excel

@Parameters

public static Collection<String[]> testData () throws IOException{

InputStream is = new FileInputStream("d://demo/data//data.xlsx");

XSSFWorkbook workbook = new XSSFWorkbook(is);

//获得工作表

XSSFSheet sheet = workbook.getSheetAt(0);

//得到总行数

int rowNum = sheet.getLastRowNum();

List<String[]> records = new ArrayList<String[]>();

for (int i = 1; i < rowNum; i++) {

//当前行

XSSFRow row = sheet.getRow(i);

int colNum = row.getLastCellNum();

String[] data = new String[colNum];

for (int j = 0; j < colNum; j++) {

data[j] = row.getCell(j).getStringCellValue();

System.out.println(data[j]);

}

records.add(data);

}

return records;

}

 

 

 

 

 

//读取EXCEL中的文件

public static Collection<String[]> getTestData(String path){

List<String[]> records = new ArrayList<String[]>();

String row;

try {

BufferedReader br =

new BufferedReader(new FileReader(path));

while ((row = br.readLine())!=null) {

String fields[] = row.split(",");

records.add(fields);

}

br.close();

} catch (Exception e) {

e.printStackTrace();

}

return records;

}

 

 

u //读取数据库参数化

@Parameters

public static Collection<String[]> testData() throws SQLException {

List<String[]> records = new ArrayList<String[]>();

//连接数据库

try {

Class.forName("com.mysql.jdbc.Driver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

Connection con = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root","");

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("select * from testdata");

//取得结果集结构

ResultSetMetaData rsMetaData = rs.getMetaData();

int cols = rsMetaData.getColumnCount();//取得例数

while(rs.next()){

String fields[] = new String[cols];

int col = 0;

for(int colIdx=1;colIdx<=cols;colIdx++) {

fields[col] = rs.getString(colIdx);

col++;

}

records.add(fields);

}

rs.close(); st.close(); con.close();

return records;

}

原文地址:https://www.cnblogs.com/stay-sober/p/4158855.html