如果浏览器在 auto-tests 期间意外关闭,则需要重新打开浏览器

Need to reopen browser if it was unexpectedly closed during auto-tests

我是 Java 的新人,有一个重要问题。 所以我有一个带有按钮 "Start Tests" 的 Java 框架,在 btn 单击时 -> chromedriver 已初始化,测试正在 Chrome 中开始。如果浏览器 window 已关闭但框架仍为 opened/visible - 我想再次单击 "Run Tests" 并再次打开浏览器 window。 但是在关闭浏览器时似乎 window - 浏览器 session ID 不再有效并且我有一个异常:Chrome 无法访问。 (Session 信息:chrome=49.0.2623.23)(Driver 信息:chromedriver=2.15.322448,平台=Windows NT 6.1 SP1 x86_64)
系统信息: host: ip: '192.168.69.3', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_55' Session 编号:934535b637b44a82c3482cc2b58471d6 Driver 信息:org.openqa.selenium.chrome.ChromeDriver

这是我的 class 用于初始化网络Driver:

public class TestBase {
  public static WebDriver driver = null;

public static WebDriver getDriver() {
        if (driver == null) {
           if (Config.getProperty("browser").equalsIgnoreCase("Chrome")) {

           File fileChrome = new File("src//test/java/chromedriver.exe");
            System.setProperty("webdriver.chrome.driver", fileChrome.getAbsolutePath());
            DesiredCapabilities chrome = DesiredCapabilities.chrome();

            try {
                driver = new ChromeDriver(chrome);
            } catch (Exception e) {
                throw new RuntimeException(e);
                }

            } else {
            System.out.println("Can't get any browser");
          }
       }
    return driver;
}

这就是我在测试中调用此方法的方式:

login = PageFactory.initElements(TestBase.getDriver(), Login.class);        
login.test1();

我认为我需要在测试开始时生成一个唯一的 session ID,并在最后杀死它。或者我应该检查 Chrome 是否打开,如果没有 - 再次启动 driver,IDK。 请帮助我解决这个问题或提出建议。我将感谢您的任何帮助或建议。谢谢

所以,经过一些尝试,我得到了答案。

添加了 healthCheck 方法,用于检查驱动程序是否存活。

private static boolean healthCheck(){
    try{
        driver.getTitle().equals(null); 
    }catch(Exception ex){
        System.out.println("Browser closed");
        return false;
    }

    return true;
}

然后,在我的 chromeDriver 从单例开始的 getDriver() 方法中,我添加了使用新方法的简单检查:

if (driver != null){
        if(healthCheck()){
            return driver;
        }
        driver = null;
    }

并且在使用 sigleton 之后 - 驱动程序开始了。

if (driver == null) {
            File fileChrome = new File("src//test/java/chromedriver.exe");
            System.setProperty("webdriver.chrome.driver", fileChrome.getAbsolutePath());

            DesiredCapabilities chrome = DesiredCapabilities.chrome();

            try {
                driver = new ChromeDriver(chrome);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        } else {
            System.out.println("Can't get any browser");
        }

现在,如果浏览器被用户意外关闭,程序会转到 healthCheck() 方法,并将再次重新打开它。在这种情况下 "Chrome not reachable"-异常消失了。