在Java中,检查Selenium WebDriver是否已退出的最佳方法 [英] In Java, best way to check if Selenium WebDriver has quit

查看:260
本文介绍了在Java中,检查Selenium WebDriver是否已退出的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一组页面对象,以查看每个对象是否已在其WebDriver上调用quit().

I need to check a collection of Page Objects to see, for each one, if quit() has been called on its WebDriver.

我编写了以下方法来检查WebDriver的状态:

I've written the following method to check a WebDriver's state:

public static boolean hasQuit(WebDriver driver) {
        try {
            driver.getTitle();
            return false;
        } catch (SessionNotFoundException e) {
            return true;
        }
}

这是问题所在:我不喜欢不得不抛出异常来发现布尔值的真相,但是自

Here's the problem: I don't like having to throw and catch an exception to discover the truth of a boolean, but it seems I have no choice since the WebDriver API doesn't provide a method to check if the driver has quit.

所以我的问题是, 是否有更好的方法来检查WebDriver是否已退出?

So my question is, is there a better way to check if a WebDriver has quit?

我发现了一个类似(且更通用)的问题

I found a similar (and more general) question here, but the question did not have any code that had been tried, and the only answer was to always set the WebDriver to null after quiting (which I don't necessarily have control over).

推荐答案

如果已调用quit(),则driver.toString()返回null:

If quit() has been called, driver.toString() returns null:

>>> FirefoxDriver: firefox on XP (null))

否则,它将返回对象的哈希码:

Otherwise, it returns a hashcode of the object:

>>> FirefoxDriver: firefox on XP (9f897f52-3a13-40d4-800b-7dec26a0c84d)

因此您可以在分配布尔值时检查是否为空:

so you could check for null when assigning a boolean:

boolean hasQuit = driver.toString().contains("(null)");

这篇关于在Java中,检查Selenium WebDriver是否已退出的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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