简体   繁体   中英

java junit test: load value dynamically from properties file

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

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 'module settings' in IntelliJ):

key=12345

Then you could load it as follows:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM