Java JUnit 测试:从属性文件动态加载值

huangapple go评论78阅读模式
英文:

java junit test: load value dynamically from properties file

问题

我想能够将'key'值存储在应用程序属性文件中。

那么当我运行我的测试类时,将使用该键值。

我应该如何将我的键值存储在属性文件中?

public class test {	
    static WebDriver driver;

    @BeforeClass
    public static void BrowserOpen() {
        driver = new ChromeDriver();
    }

    @Test
    public void test() {
        int key = 12345;
    }	 

    @AfterClass
    public static void BrowserClose() {
        driver.quit();
    }
}
英文:

I have a junit test class like below:

I want to be able to store the 'key' value in a application properties file.

So when i run my test class, the key value is used.

how will i store my key values in a properties file?

public class test {	
	static WebDriver driver;


	@BeforeClass
    public static void BrowserOpen() {
	    driver = new ChromeDriver();
    }

    @Test
    public void test() {
	    int key = 12345;
    }	 

    @AfterClass
    public static void BrowserClose() {
	    driver.quit();
    }
}

答案1

得分: 0

假设您将以下内容放入您的资源或测试资源文件夹中的`example.properties`(该文件夹在构建工具中配置如Maven或Gradle配置或IntelliJ中的模块设置):

```java
key=12345

然后您可以按如下方式加载它:

import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {
    private static int key;

    @BeforeClass
    public static void loadKey() throws IOException {
        Properties properties = new Properties();
        properties.load(PropertiesExample.class.getResourceAsStream("example.properties"));
        key = Integer.parseInt(properties.getProperty("key"));
    }

    @Test
    public void test() {
        System.out.println(key); // 打印 12345
    }
}

<details>
<summary>英文:</summary>

Suppose you put the following in `example.properties` in your resources or test-resources folder (that folder is configured in your build tool - such as your Maven or Gradle config or the &#39;module settings&#39; in IntelliJ):

key=12345


Then you could load it as follows:

```java
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {
    private static int key;

    @BeforeClass
    public static void loadKey() throws IOException {
        Properties properties = new Properties();
        properties.load(PropertiesExample.class.getResourceAsStream(&quot;example.properties&quot;));
        key = Integer.parseInt(properties.getProperty(&quot;key&quot;));
    }

    @Test
    public void test() {
        System.out.println(key); // prints 12345
    }
}

huangapple
  • 本文由 发表于 2020年8月5日 12:49:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63258598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定