问题
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.)
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
.)
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);
The custom variables would be present in the environment of the geckodriver process and the environment of the Firefox process.
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?
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.).
回答1:
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);
回答2:
Would this website help? https://testautomationarchives.blogspot.com/2013/08/how-to-configure-selenium-webdriver.html.
Starting at Step 5 from the above site, since 1-4 are installing things:
Step 5 : Set Environment Variables (Windows 7 )
- Right Click On Computer
- Click on Properties
- Click On ‘Advance Settings’
- On ‘System Properties ‘ Click On tab ‘Advance’
- Click on ‘Environment Variables ‘
- Copy following path where JDK is installed. C:\Program Files\Java\jdk1.6.0\bin
- On Environment Variable Window Click ‘New’ Under System Variable and Set Path: C:\Program Files\Java\jdk1.6.0\bin. If Path Variable already Exist Then Edit it .
- Set CLASSPATH : Copy following Path Where JDK is installed :
- On Environment Variable Window Click ‘New’ under User Variables and Set CLASSPATH :
- Enviornment is set up now start JAVA IDE
来源:https://stackoverflow.com/questions/44057317/how-do-i-set-environment-variables-for-selenium-java-firefoxdriver