【问题标题】:Elegant way to init or inject string into a static field beforeClass (JUNIT) from spring configuration?从弹簧配置中初始化或将字符串注入静态字段 beforeClass (JUNIT) 的优雅方法?
【发布时间】:2017-07-17 22:56:05
【问题描述】:

如果您想将数据注入 静态字段,注释 @Value("${my.field}") 可以很好地工作。

就我而言,我正在为我的 Spring Boot 应用程序构建测试。我正在使用Junit。我有一些任务要做 @BeforeClass,我需要一些来自 spring 应用程序配置的属性。我正在寻找一种优雅的方式来获取我的属性。

【问题讨论】:

  • 您可以在测试类中自动装配环境并从 env.getproperty("propertyname") 获取属性
  • **@Autowired Environment 环境 ** 不是静态的。在@beforeClass(静态方法)中,我不能使用“环境”。
  • 您能否分享一下您正在尝试的内容。如果您希望在测试类中加载某些属性,您可以@Autowired Environment 环境并使用@PostConstruct 方法来初始化所需的属性。

标签: spring spring-mvc spring-boot junit


【解决方案1】:

您可以自行在静态设置方法中加载属性文件并选择测试所需的值。对于某些人来说,它可能不如使用 @Value 注入方便,但它会成功。

public class SomeTestClass {

    private static String myProperty;

    @BeforeClass
    public static void setUpClass() throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/main/resources/application.properties"));
        myProperty = prop.getProperty("your.property.key");
    }

    @Test
    public void shouldLoadProperty() throws Exception {
        assertEquals("expectedValue", myProperty);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    相关资源
    最近更新 更多