Selenium 2(WebDriver):在调用Alert.getText()之前检查文本是否存在

时间:2011-07-19 17:31:35

标签: alertdialog webdriver selenium-webdriver

我遇到了Checking If alert exists before switching to it中描述的问题。抓住NullPointerException我觉得太可怕了。有没有人更优雅地解决这个问题?

我当前的解决方案使用捕获NPE的等待。客户端代码只需调用waitForAlert(driver, TIMEOUT)

/**
 * If no alert is popped-up within <tt>seconds</tt>, this method will throw
 * a non-specified <tt>Throwable</tt>.
 * 
 * @return alert handler
 * @see org.openqa.selenium.support.ui.Wait.until(com.​google.​common.​base.Function)
 */
public static Alert waitForAlert(WebDriver driver, int seconds) {
    Wait<WebDriver> wait = new WebDriverWait(driver, seconds);
    return wait.until(new AlertAvailable());
}

private static class AlertAvailable implements ExpectedCondition<Alert> {
    private Alert alert = null;
    @Override
    public Alert apply(WebDriver driver) {
        Alert result = null;
        if (null == alert) {
            alert = driver.switchTo().alert();
        }

        try {
            alert.getText();
            result = alert;
        } catch (NullPointerException npe) {
            // Getting around https://groups.google.com/d/topic/selenium-users/-X2XEQU7hl4/discussion
        }
        return result;
    }
}

2 个答案:

答案 0 :(得分:2)

FluentWait.until()

的JavaDoc
  

反复将此实例的输入值应用于给定函数,直到出现以下情况之一:

     
      
  1. 该函数既不返回null也不返回false,
  2.   
  3. 该函数抛出一个未标记的异常,
  4.   
  5. 超时到期   .......(剪断)
  6.   

由于NullPointerException表示错误条件,而WebDriverWait仅忽略NotFoundException,因此只需删除try / catch块即可。 Exception中未经检查的,未标记的apply()在语义上等同于在现有代码中返回null

private static class AlertAvailable implements ExpectedCondition<Alert> {
    @Override
    public Alert apply(WebDriver driver) {
        Alert result = driver.switchTo().alert();
        result.getText();
        return result;
    }
}

答案 1 :(得分:2)

基于@Joe Coder answer,这个等待的简化版本将是:

/**
 * If no alert is popped-up within <tt>seconds</tt>, this method will throw
 * a non-specified <tt>Throwable</tt>.
 * 
 * @return alert handler
 * @see org.openqa.selenium.support.ui.Wait.until(com.​google.​common.​base.Function)
 */
public static Alert waitForAlert(WebDriver driver, int seconds) {
    Wait<WebDriver> wait = new WebDriverWait(driver, seconds)
        .ignore(NullPointerException.class);
    return wait.until(new AlertAvailable());
}

private static class AlertAvailable implements ExpectedCondition<Alert> {
    @Override
    public Alert apply(WebDriver driver) {
        Alert alert = driver.switchTo().alert();
        alert.getText();
        return alert;
    }
}

我写了一个简短的测试来证明这个概念:

import com.google.common.base.Function;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestUntil {
    private static Logger log = LoggerFactory.getLogger(TestUntil.class);

    @Test
    public void testUnit() {
        Wait<MyObject> w = new FluentWait<MyObject>(new MyObject())
                .withTimeout(30, TimeUnit.SECONDS)
                .ignoring(NullPointerException.class);
        log.debug("Waiting until...");
        w.until(new Function<MyObject, Object>() {
            @Override
            public Object apply(MyObject input) {
                return input.get();
            }
        });
        log.debug("Returned from wait");
    }

    private static class MyObject {
        Iterator<Object> results = new ArrayList<Object>() {
            {
                this.add(null);
                this.add(null);
                this.add(new NullPointerException("NPE ignored"));
                this.add(new RuntimeException("RTE not ignored"));
            }
        }.iterator();
        int i = 0;
        public Object get() {
            log.debug("Invocation {}", ++i);
            Object n = results.next();
            if (n instanceof RuntimeException) {
                RuntimeException rte = (RuntimeException)n;
                log.debug("Throwing exception in {} invocation: {}", i, rte);
                throw rte;
            }
            log.debug("Result of invocation {}: '{}'", i, n);
            return n;
        }
    }
}

在此代码中,untilMyObject.get()被调用了四次。第三次,它抛出一个被忽略的异常,但最后一个抛出一个未被忽略的异常,中断了等待。

输出(为便于阅读而简化):

Waiting until...
Invocation 1
Result of invocation 1: 'null'
Invocation 2
Result of invocation 2: 'null'
Invocation 3
Throwing exception in 3 invocation: java.lang.NullPointerException: NPE ignored
Invocation 4
Throwing exception in 4 invocation: java.lang.RuntimeException: RTE not ignored

------------- ---------------- ---------------
Testcase: testUnit(org.lila_project.selenium_tests.tmp.TestUntil):  Caused an ERROR
RTE not ignored
java.lang.RuntimeException: RTE not ignored
    at org.lila_project.selenium_tests.tmp.TestUntil$MyObject$1.<init>(TestUntil.java:42)
    at org.lila_project.selenium_tests.tmp.TestUntil$MyObject.<init>(TestUntil.java:37)
    at org.lila_project.selenium_tests.tmp.TestUntil$MyObject.<init>(TestUntil.java:36)
    at org.lila_project.selenium_tests.tmp.TestUntil.testUnit(TestUntil.java:22)

请注意,由于RuntimeException未被忽略,因此不会打印“从等待返回”日志。

相关问题