在IntelliJ中能否永久设置webdriver.http.factory系统属性?
问题描述
我之前运行Selenium测试时遇到问题,靠添加以下依赖和在测试前执行一行代码解决了问题:
依赖:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-http-jdk-client</artifactId> <version>4.5.0</version> </dependency>
解决代码:
System.setProperty("webdriver.http.factory", "jdk-http-client");
目前我的测试代码结构如下:
public class seleniumTest { WebDriver driver; @BeforeEach void setup(){ System.setProperty("webdriver.http.factory", "jdk-http-client"); driver = WebDriverManager.chromedriver().create(); } @AfterEach void teardown(){ driver.quit(); } @Test void test(){ } }
现在我想知道有没有办法永久设置这个系统属性,不用每次写代码都加System.setProperty语句。我在MacOS BigSur的IntelliJ安装目录里找到了idea.vmoptions和idea.properties文件,但不知道配置系统属性的语法,也不确定这么做是否可行。
解决方案
首先明确:idea.vmoptions和idea.properties是用来配置IntelliJ IDEA自身运行参数的,无法直接设置你的测试程序的系统属性,别搞错了。下面是几种可行的永久配置方式:
1. IntelliJ IDEA全局测试配置(所有新项目自动生效)
- 点击顶部菜单栏
Run→Edit Configurations - 在左侧列表找到你的测试框架(比如JUnit),选中对应的默认模板(不是单个配置)
- 在
VM options输入框中填入:-Dwebdriver.http.factory=jdk-http-client - 点击
Apply保存,之后新建的测试类运行时会自动带上这个参数
2. 项目级Maven配置(仅当前项目生效)
如果用Maven管理项目,在pom.xml中给surefire-plugin添加系统属性配置:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.1.2</version> <configuration> <systemPropertyVariables> <webdriver.http.factory>jdk-http-client</webdriver.http.factory> </systemPropertyVariables> </configuration> </plugin> </plugins> </build>
之后用mvn test运行测试时,会自动注入该系统属性。
3. 系统级环境变量配置(所有Java程序生效)
在MacOS中:
- 打开终端,编辑Shell配置文件(zsh用户编辑
~/.zshrc,bash用户编辑~/.bash_profile) - 添加一行:
export _JAVA_OPTIONS="-Dwebdriver.http.factory=jdk-http-client" - 执行
source ~/.zshrc(或对应文件)使配置立即生效
这样所有Java程序启动时都会自动加载这个系统属性。
4. 当前项目单独配置
如果只想让当前项目的测试生效:
- 打开
Run→Edit Configurations,选中你的测试配置 - 在
VM options中添加-Dwebdriver.http.factory=jdk-http-client - 点击
Apply保存即可
内容的提问来源于stack exchange,提问作者CowOO
相关产品推荐
相关产品推荐

