多くの場合、この問題は、テスト中のシステムの予測できない場所で発生するという点で厄介です。現時点では、これらの不確実性をすべて webdriver の構成によって自動的に処理する方法が存在するとは思いません。私の一般的なアドバイスは、webDriver を Proxy でラップし、ある種の動的プロキシを使用してすべての webdriver メソッドをラップすることです。このようにして、予測できないアラートを一元的に制御し、ログを作成したり、メソッドのパフォーマンスを評価したり、ランダムな unreachableBrowser 例外を処理したり、ランダムな 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();
}
}