1)验证标题
package com.learningselenium.normalwebdriver;
import static org.junit.Assert.*;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class test MultipleWindowsTile{
WebDriver driver = new FirefoxDriver();
@Before
public void setUp() throws Exception{
driver.get("http://www.w3schools.com/jsref/met_win_open.asp");
}
@Test
public void testMultipleWindowsTitle() throws Exception{
//打开父窗口,并记录下父窗口的控点
String parentWindowId = driver.getWindowHandle();
//验证父窗口的完整标题是Window open() Method
assertEquals("Window open() Method", driver.getTitle());
WebElement tryItButton = driver.findElement(By.xpath("//*[@id = \"main\"]/div[2]/a"));
tryItButton.click();
//获取所有打开窗口的控点列表
Set<String> allWindowsId = driver.getWindowHandles();
for(String windowId : allWindowsId){
if(driver.switchTo().window(windowId).getTitle().contains("Tryit")){
driver.switchTo().window(windowId);
break;
}
}
assertEquals("Tryit Editor v1.8", driver.getTitle());
//通过父窗口的控点再次切换回原父窗口,并再次验证其完整标题为Window open() Method,确认此处窗口切换成功
driver.switchTo().window(parentWindowId );
assertEquals("Window open() Method", driver.getTitle());
}
@After
public void tearDown() throws Exception{
driver.quit();
}
}
2)验证内容
...
for(String windowId : allWindowsId){
if(driver.switchTo().window(windowId).getPageSource().contains("open a new brower window")){
driver.switchTo().window(windowId);
break;
}
}
...