gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:13:28 34 4
gpt4 key购买 nike

我一直在使用 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com