书接上回,最近项目里边新的release需要move to uat。然后我很光荣的被委派去给tester执行自动化测试脚本做support,让我极度遗憾的是tester不是妹子,表示本丝注定单身孤独终老的命啊。
好吧不扯淡了,在测试的过程中碰到几个问题导致程序不够稳定,脚本也被喷不够robust,我自己也喷page object模式就是shit,维护的人会shi的很难看。
1. 处理popup window问题处理的不够好?
a. 切换到新弹出的window
public boolean switchToWindowAttach(WebDriver driver, String windowTitle,String frameId) { boolean flag = false; try { //记下当前window String currentHandle = getDriver().getWindowHandle(); Sethandles = 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
/** * 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. 需要等待页面的某个元素加载完成再做后续操作?
Selenium提供了2个等待的操作,一种是隐式的,另一种,er,也不知道是不是叫现实的
a.
public void waitForElementLoading(Long millis) { driver.manage().timeouts().implicitlyWait(millis, TimeUnit.MILLISECONDS); }
b.
public WebElement waitForElementByLocator(final By locator, Long timeOut) { if (timeOut == null) { timeOut = 60L; } WebElement id = (new WebDriverWait(getDriver(), timeOut)) .until(new ExpectedCondition() { @Override public WebElement apply(WebDriver d) { return d.findElement(locator); } }); return id; }
第一个就是隐式的等待啦。第二种我自己隐式的实现了ExceptedCondition,它的apply方法应该会被回调。
ExceptedCondition提供了许多静态的方法大家可以根据自己的需求来使用。
这两种等待的区别和具体使用需要本丝研究一把,下次给大家介绍哈。额,表喷我,这准备不足真心讲不好。