如何为Selenium Java FirefoxDriver设置环境变量? [英] How do I set environment variables for Selenium Java FirefoxDriver?

查看:87
本文介绍了如何为Selenium Java FirefoxDriver设置环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java单元测试中,我想使用Selenium在Firefox上测试我的网页.我的测试要求我为Firefox设置环境变量.(具体来说,我想设置DISPLAY变量.)

From within Java unit tests, I want to use Selenium to test my web page with Firefox. My tests require that I set an environment variable for Firefox. (Specifically, I want to set the DISPLAY variable.)

FirefoxBinary 类具有方法

The FirefoxBinary class has a method setEnvironmentProperty, which sounds like it should set environment variables for the environment the Firefox process runs in, but in practice it does not have that effect. (I have confirmed that with cat /proc/<firefox_pid>/environ.)

回到selenium-java 3.0.1,我可以使用自定义环境变量构建 GeckoDriverService ,并且 FirefoxDriver 构造函数接受驱动程序服务作为参数,就像这样:

Back with selenium-java 3.0.1, I could build a GeckoDriverService with custom environment variables, and the FirefoxDriver constructor accepted the driver service as an argument, like so:

Map<String, String> customEnvironmentMap = new HashMap<>();
customEnvironmentMap.put("DISPLAY", ":1");
GeckoDriverService driverService = new GeckoDriverService.Builder(binary)
        .withEnvironment(customEnvironmentMap)
        .usingPort(0)
        .build()
FirefoxDriver driver = new FirefoxDriver(driverService, capabilities, null);

自定义变量将出现在geckodriver进程的环境和Firefox进程的环境中.

The custom variables would be present in the environment of the geckodriver process and the environment of the Firefox process.

版本3.4.0中不存在该构造函数,并且 FirefoxDriver 使用私有方法创建驱动程序服务,因此我无法对其进行自定义.那么,如何配置Selenium启动的Firefox进程的环境?

That constructor is not present in version 3.4.0, and FirefoxDriver uses a private method to create the driver service, so I can't customize it. So, how do I configure the environment of the Firefox process that Selenium launches?

我当前的解决方法是用类似的脚本替换geckodriver可执行文件路径:

My current workaround is to substitute a script like this one for the geckodriver executable path:

#!/bin/bash
exec /usr/bin/env DISPLAY=:1 /path/to/geckodriver $@

由于种种原因,我不太喜欢这种技术(这很麻烦,我必须在文件系统中为脚本创建一个临时文件,等等.)

I don't really like this technique, for various reasons (it's hacky, I have to create a temp file for the script in the filesystem, etc.).

推荐答案

从Selenium 3.7.1开始,采用 GeckoDriverService 的构造函数已返回,因此您可以再次执行以下操作:

As of Selenium 3.7.1, the constructor that takes a GeckoDriverService has returned, so you can once again do the following:

Map<String, String> environment = new HashMap<>();
environment.put("DISPLAY", ":1");
GeckoDriverService service = new GeckoDriverService.Builder()
        .usingAnyFreePort()
        .withEnvironment(environment)
        .build();
FirefoxDriver driver = new FirefoxDriver(service);

这篇关于如何为Selenium Java FirefoxDriver设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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