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

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

java junit test: load value dynamically from properties file

问题

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

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

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

  1. public class test {
  2. static WebDriver driver;
  3. @BeforeClass
  4. public static void BrowserOpen() {
  5. driver = new ChromeDriver();
  6. }
  7. @Test
  8. public void test() {
  9. int key = 12345;
  10. }
  11. @AfterClass
  12. public static void BrowserClose() {
  13. driver.quit();
  14. }
  15. }
英文:

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?

  1. public class test {
  2. static WebDriver driver;
  3. @BeforeClass
  4. public static void BrowserOpen() {
  5. driver = new ChromeDriver();
  6. }
  7. @Test
  8. public void test() {
  9. int key = 12345;
  10. }
  11. @AfterClass
  12. public static void BrowserClose() {
  13. driver.quit();
  14. }
  15. }

答案1

得分: 0

  1. 假设您将以下内容放入您的资源或测试资源文件夹中的`example.properties`该文件夹在构建工具中配置MavenGradle配置或IntelliJ中的模块设置):
  2. ```java
  3. key=12345

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

  1. import org.junit.BeforeClass;
  2. import org.junit.Test;
  3. import java.io.IOException;
  4. import java.util.Properties;
  5. public class PropertiesExample {
  6. private static int key;
  7. @BeforeClass
  8. public static void loadKey() throws IOException {
  9. Properties properties = new Properties();
  10. properties.load(PropertiesExample.class.getResourceAsStream("example.properties"));
  11. key = Integer.parseInt(properties.getProperty("key"));
  12. }
  13. @Test
  14. public void test() {
  15. System.out.println(key); // 打印 12345
  16. }
  17. }
  1. <details>
  2. <summary>英文:</summary>
  3. 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

  1. Then you could load it as follows:
  2. ```java
  3. import org.junit.BeforeClass;
  4. import org.junit.Test;
  5. import java.io.IOException;
  6. import java.util.Properties;
  7. public class PropertiesExample {
  8. private static int key;
  9. @BeforeClass
  10. public static void loadKey() throws IOException {
  11. Properties properties = new Properties();
  12. properties.load(PropertiesExample.class.getResourceAsStream(&quot;example.properties&quot;));
  13. key = Integer.parseInt(properties.getProperty(&quot;key&quot;));
  14. }
  15. @Test
  16. public void test() {
  17. System.out.println(key); // prints 12345
  18. }
  19. }

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:

确定