java - 使用 java 所有者 aeonbits 进行测试

标签 java unit-testing testing owner

我一直在使用 java OWNER 进行基于属性的配置。

我创建了一个静态方法

public static final ApplicationConfiguration config = ConfigFactory.create(ApplicationConfiguration.class,
        System.getProperties(), System.getenv());

然后我在需要 conf 的任何地方导入该类。

不用说,单元测试是一个 PITA。我找不到覆盖配置中值的好方法。

我想避免在每个类中将配置作为依赖项传递。 它增加了很多冗长,从设计的角度来看没有意义。 同样适用于在每个类中调用配置工厂

ApplicationConfiguration config = ConfigFactory.create(ApplicationConfiguration.class,
        System.getProperties(), System.getenv());

你有什么建议吗?有最佳实践吗?

最佳答案

两件事:

  1. 您可以创建一个提供属性的类,所有用户都可以使用它:

    public class PropertiesAccessor {
    
       private static MyConfiguration mMyConfig = ConfigFactory.create(MyConfiguration.class);
    
       private PropertiesAccessor() 
          // No need to allow instantiation of this class
       }
    
       /**
        * Get properties for this application
        *
        * @return Properties
        */
       public static MyConfiguration getProperties() {
          return mMyConfig;
       }
    
       // for unit testing
       @VisibleForTesting
       public static void setProperties(MyConfiguration config) {
          mMyConfig = config;
       }
    }
    

    现在,任何需要属性的地方,都可以使用这个静态方法

    PropertiesAccessor.getProperties()
    
  2. 请注意,有一个测试方法 setProperties()。有多种使用此方法的方法。您可以创建一个测试属性文件,加载它,然后调用 setProperties() 方法。我喜欢这样的实用方法:

    public static void initProperties(String fileName) {    
    
       Properties testProperties = new Properties();    
    
       File file = new File(fileName);
       FileInputStream stream = null;   
       try {    
          stream = new FileInputStream(file);   
          testProperties.load(stream);  
       } catch (IOException e) {    
          // Log or whatever you want to do
       } finally {  
          if (stream != null) {
          try { 
             stream.close();    
       } catch (IOException e) {    
         // Log or whatever you want to do; 
       }    
    
       MyConfiguration config = ConfigFactory.create(MyConfiguration.class, testProperties);    
       PropertiesAccessor.setProperties(config);
    }
    

    然后,您可以拥有各种属性文件。

    或者,如果您只想设置一些属性,请执行以下操作:

     Properties testProperties = new Properties();
     testProperties.setProperty("key1", "data1");
     testProperties.setProperty("key2", "data2");
     final MyConfiguration myConfig = ConfigFactory.create(MyConfiguration.class, testProperties);
     PropertiesAccessor.setProperties(myConfig);
    

关于java - 使用 java 所有者 aeonbits 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52188820/

相关文章:

java - wldeploy 部署文件夹中的所有文件

c# - 单元测试 Web App 时如何模拟应用程序路径

php - 与用户一起创建单元测试

python - 如何编写分离不同类型测试的 nose2 插件?

ruby-on-rails - 我无法引导 Spork 配置

javascript - 测试用例失败后的 Jest 清理

java - 如何设置 IntelliJ IDEA 14 以在可能的情况下添加 "final"关键字?

java - 仅有时从 actionPerformed 函数调用 Pack 方法

java - Java 中的 DFS 和 SMB(jcifs) 问题

Android:如何保存、清除然后恢复 SharedPreferences 以进行单元测试?