英文:
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 'module settings' 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("example.properties"));
key = Integer.parseInt(properties.getProperty("key"));
}
@Test
public void test() {
System.out.println(key); // prints 12345
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论