You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium WebDriver Java 如何统一声明并在所有代码中调用账号密码

解决方案

核心思路是将账号密码等敏感信息和业务代码解耦,统一存储在独立的配置载体中,代码仅负责读取调用,修改配置无需改动任何业务逻辑代码,完全满足你统一声明、全局调用的需求,以下是不同场景下的可用方案:

方案1:轻量properties配置文件方案(Java生态通用,无需额外依赖)

  • 步骤1:在项目的resources目录下新建config.properties配置文件,写入配置内容:
# 测试环境配置
test.url=https://forme-hml.alterdata.com.br/
login.account=user.dsn.shop
login.password=senha

注意:务必将config.properties加入.gitignore规则,避免敏感信息提交到代码仓库造成泄露

  • 步骤2:编写全局统一的配置读取工具类,所有代码都可以复用该类读取配置:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigReader {
    private static final Properties properties = new Properties();

    static {
        try (InputStream inputStream = ConfigReader.class.getClassLoader().getResourceAsStream("config.properties")) {
            if (inputStream == null) {
                throw new RuntimeException("找不到config.properties配置文件");
            }
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件失败", e);
        }
    }

    public static String get(String configKey) {
        return properties.getProperty(configKey);
    }
}
  • 步骤3:改造原有测试代码,替换硬编码内容即可:
public class Cadastro_Produto_ERP4ME {

    @Test
    public void iniciar_cadastro() throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get(ConfigReader.get("test.url"));
        Thread.sleep(1000);
        driver.findElement(By.id("email-login")).sendKeys(ConfigReader.get("login.account"));
        driver.findElement(By.xpath("//form/div[2]/div/input")).sendKeys(ConfigReader.get("login.password"));
        // 剩余业务逻辑保持不变
    }
}

方案2:环境变量方案(安全性更高,适合CI/CD流水线场景)

无需在项目中存储配置文件,直接把账号密码设置为系统环境变量,代码通过JDK自带方法读取即可:

// 读取系统环境变量中的账号密码,环境变量名可自定义
String account = System.getenv("TEST_LOGIN_ACCOUNT");
String password = System.getenv("TEST_LOGIN_PASSWORD");

流水线执行测试任务时直接注入环境变量即可,不会出现敏感信息明文存储的问题。

方案3:Spring项目注解方案(适用于基于Spring框架的测试项目)

如果项目已经集成Spring,可直接用@Value注解读取配置文件或配置中心的内容,无需手动编写工具类:

@Value("${login.account}")
private String account;

@Value("${login.password}")
private String password;

内容的提问来源于stack exchange,提问作者Thiago Andrade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 01:09:01