Selenium 2(WebDriver):在调用Alert.getText()之前检查文本是否存在 [英] Selenium 2 (WebDriver): check that text exists before calling Alert.getText()

查看:274
本文介绍了Selenium 2(WebDriver):在调用Alert.getText()之前检查文本是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了中所述的问题,请检查是否存在警报。我发现捕获 NullPointerException 很可怕。有人能更优雅地解决这个问题吗?

I came across the problem described in Checking If alert exists before switching to it. I find horrible to capture a NullPointerException. Has anyone solved this problem more elegantly?

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

My current solution uses a wait that captures the NPE. The client code just have to invoke 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;
    }
}


推荐答案

基于在@Joe Coder上 answer ,此等待的简化版本为:

Based upon @Joe Coder answer, a simplified version of this wait would be:

/**
 * 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;
    }
}

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

I have written a short test to proof the concept:

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;
        }
    }
}

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

In this code, in the until the MyObject.get() is invoked four times. The third time, it throws an ignored exception, but the last one throws a not-ignored exception, interrupting the wait.

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

The output (simplified for readability):

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 ,因此不会返回从等待返回日志

Note that as the RuntimeException is not ignored, the "Returned from wait" log is not printed.

这篇关于Selenium 2(WebDriver):在调用Alert.getText()之前检查文本是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆