首页 > 解决方案 > java junit test:从属性文件动态加载值

问题描述

我有一个如下的junit测试类:

我希望能够将“键”值存储在应用程序属性文件中。

所以当我运行我的测试类时,会使用键值。

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

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();
    }
}

标签: javajunit

解决方案


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

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); // prints 12345
    }
}

推荐阅读