java - 从属性文件加载不同的集成

标签 java selenium jvm testng properties-file

我正在大学开展一个期末项目,但遇到了一个特殊问题。我正在使用 TestNG 和 Selenium 测试某些网站如何在本地主机中工作。现在,我有不同的集成,这意味着它使用属性文件中配置的不同数据库。我希望我可以在 JVM 或命令行中传递参数,例如“integration1”,它会从属性文件中捕获该字段。我在网上找到的唯一内容是关于 Spring 配置文件,但这没有帮助,因为它是一个普通的 java 项目。这是一个代码:

默认属性

db_driver = com.mysql.jdbc.Driver
db_path = jdbc:mysql://localhost:3306/dana?useUnicode=true&characterEncoding=UTF-8

user.properties(它检查 user.properties 文件中是否存在某个字段,如果存在,则使用该字段而不是默认值,这对团队中的其他成员很有用,因为每个配置都不同)

db_driver = com.mysql.jdbc.Driver
db_path_elixir = jdbc:mysql://localhost:3306/elixir?useUnicode=true&characterEncoding=UTF-8
db_path_dana = jdbc:mysql://localhost:3306/dana?useUnicode=true&characterEncoding=UTF-8
#db_path - actual path which will be used if user passes "dana" or "elixir" as arguments
#my logic would be something like db_path = jdbc:mysql://localhost:3306/ + ${integration} + ?useUnicode=true&characterEncoding=UTF-8

这些属性文件在ConfigurationService类中配置

ConfigurationService.java

...
private String getProperty(String key) {
    if (userProperties.containsKey(key)) {
        return userProperties.getProperty(key);
    }
    return defaultProperties.getProperty(key);
}

最佳答案

您可以按如下方式修改您的 ConfigurationService,并从命令行将属性传递为 java -Dkey=value

private String getProperty(String key){
    String value = null;
    if (System.getProperties().contains(key))
        value = System.getProperty(key);
    else if (userProperties.containsKey(key))
        value = userProperties.getProperty(key);
    else
        value = defaultProperties.getProperty(key);
}

您还可以如下初始化您的 ConfigurationService 实例

Properties properties;
public void init(){
 properties.putAll(defaultProperties);
 properties.putAll(userProperties);
 properties.putAll(System.getProperties());
}

然后修改您的 getProperty 方法如下

private String getProperty(String key){
        return properties.getProperty(key);
}

这里 putAll 调用的顺序很重要。当您再次输入相同的键值时,先前的值将被覆盖。

关于java - 从属性文件加载不同的集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56558601/

相关文章:

java - G1 垃圾收集器是否默认启用了字符串去重功能?

java - 在 toString 方法中尝试 Catch block

java - 查找eclipse中编译过程中使用的类

Python selenium 无法点击按钮

javascript - 检查元素是否未显示 - WebDriverJS

java - 如果没有余数,双除法等于整数除法吗?

java - JVM 会垃圾收集内存中的孤立周期吗?

java - 一个线程可以访问同步非静态方法,而另一个线程可以同时访问同步静态方法吗?

javascript - Wicket AjaxNewWindowNotifyingBehavior 和后退按钮

python - Selenium:远程在我的机器上运行测试?