更常见的是,这个问题很麻烦,因为它出现在被测系统中不可预测的地方。现在,我认为没有办法通过 webdriver 中的配置来自动处理所有这些 uncretainities。我的一般建议是将 webDriver 包装在 Proxy 中,并使用某种动态代理来包装所有 webdriver 方法。通过这种方式,您可以对不可预测的警报进行单点控制,进行日志记录或评估方法性能,处理随机无法访问的浏览器异常,处理随机 StaleElementException 等。我发现这对于各种情况都非常有用,但性能损失很小.
Class WebDriverProxy implements InvocationHandler{
WebDriverWrapperImpl impl = new WebDriverWrapperImpl();
public String clickByXPath(String xpath) {
return (String)handleInvocation(impl,"clickByXPath", new Object[]{xpath});
// return impl.clickByXPath( xpath) ;
}
/**All fail fast strategies could be centralized here., no need of any assertion errors in libraries,
* However it makes sense to wrap webdriver exceptions as either recoverable or nonrecoverable
* recoverable ones are like unexpected hangs on the browser, which could be handled at the test runner level, wherein the
* whole test can be retried.
* irrecoverable ones are also mostly handled at the test runner level, but capable of being caught at the test script level *
**/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Object o = null;
Throwable target = null;
try{
o = method.invoke(proxy, args);
}
catch(InvocationTargetException ee){
target = ee.getTargetException();
throw target;
}
return o;
}
public Object handleInvocation(Object proxy, String method, Object[] args){
Object toReturn = null;
Method m = null;
Class[] classes = new Class[args.length];
for(int i = 0;i<args.length;i++){
classes[i]=String.class;
}
for(Object x:args){
logBuffer.append(x.toString()+",");
}
log.trace("WebDriverProxy. "+method+"("+logBuffer.toString()+")");
logBuffer = new StringBuffer();
try{
m = proxy.getClass().getMethod(method,classes);
toReturn = invoke(proxy,m, args);
}catch(NoSuchMethodException e){
e.printStackTrace();
}catch( StaleElementReferenceException e){
log.debug("Exception was of tye "+e.getClass().getCanonicalName());
}
catch(UnreachableBrowserException | NoSuchElementException e){
log.debug("Exception was of tye "+e.getClass().getCanonicalName());
//If the NoSuchelement is due to suspect Alerts being present, switchToAlert() and alert.accept() here.
}
return toReturn;
}
}
class WebDriverWrapperImpl {
WebDriver driver = new ChromeDriver();
public String clickByXPath(String xpath) throws Exception{
driver.findElement(By.Xpath(xpath)).click();
return driver.getTitle();
}
}