Selenium 使用要点记录<二>

书接上回,最近项目里边新的release须要move to uat。而后我很光荣的被委派去给tester执行自动化测试脚本作support,让我极度遗憾的是tester不是妹子,表示本丝注定单身孤独终老的命啊。java

好吧不扯淡了,在测试的过程当中碰到几个问题致使程序不够稳定,脚本也被喷不够robust,我本身也喷page object模式就是shit,维护的人会shi的很难看。app

1. 处理popup window问题处理的不够好?ide

    a. 切换到新弹出的window测试

        public boolean switchToWindowAttach(WebDriver driver, String windowTitle,String frameId) {
		boolean flag = false;
		try {
		        //记下当前window
			String currentHandle = getDriver().getWindowHandle();
			Set<String> handles = getDriver().getWindowHandles();
			for (String s : handles) {
				if (s.equals(currentHandle)) {
					continue;
				} else {
					driver.switchTo().window(s);
					if (driver.getTitle().contains(windowTitle)) {
					    if(!StringUtils.isBlank(frameId)){
					        //有些window可能要切换到具体的iframe才能操做内部元素
					        //getDriver().switchTo().defaultContent() 切换回外层
						driver.switchTo().frame(frameId);
						}
						flag = true;
						loggerContxt.info("Switch to window: " + windowTitle
								+ " successfully!");
						break;
					} else {
					        //若是当前循环到的window不是须要切换的window则切换回最初window
						driver.switchTo().window(currentHandle);
						continue;
					}
				}
			}
		} catch (NoSuchWindowException e) {
			loggerContxt.fatal(String.format("Failed to swith to window whose title contains:: ", windowTitle),e);
			flag = false;
		}
		return flag;
	}

    b. 关掉处理完成的popup window
spa

/**
 * close popup window by the title name
 * @param driver WebDriver
 * @param title the title of the window need to be closed
 * @param orginalHandle the Window Handler of current window 
 * @return
 */
 protected void closePopupByTitle(WebDriver driver, String title,
			String orginalHandle) {
		for (String handle : driver.getWindowHandles()) {
			String theTitle = driver.switchTo().window(handle).getTitle();
			//if the title are samilar, then close
			if (theTitle.contains(title)) {
				driver.close();
			}
			//switch back to the original window
			if (!handle.equalsIgnoreCase(orginalHandle)) {
				driver.switchTo().window(orginalHandle);
			}
		}
	}

2. 须要等待页面的某个元素加载完成再作后续操做?code

Selenium提供了2个等待的操做,一种是隐式的,另外一种,er,也不知道是否是叫现实的orm

a.ci

public void waitForElementLoading(Long millis) {
	    driver.manage().timeouts().implicitlyWait(millis, TimeUnit.MILLISECONDS);
	}

b.
get

public WebElement waitForElementByLocator(final By locator, Long timeOut) {
		if (timeOut == null) {
			timeOut = 60L;
		}
		WebElement id = (new WebDriverWait(getDriver(), timeOut))
				.until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver d) {
						return d.findElement(locator);
					}
				});
		return id;
		
		
	}

第一个就是隐式的等待啦。第二种我本身隐式的实现了ExceptedCondition,它的apply方法应该会被回调。iframe

ExceptedCondition提供了许多静态的方法你们能够根据本身的需求来使用。

这两种等待的区别和具体使用须要本丝研究一把,下次给你们介绍哈。额,表喷我,这准备不足真心讲很差。

相关文章
相关标签/搜索