Java 解决 JUnit 测试中的 Spring @Value 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20879608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:58:04  来源:igfitidea点击:

Resolve Spring @Value expression in JUnit tests

javaspringjunitjunit4spring-3

提问by Harold L. Brown

Here's a snippet of a Spring bean:

这是 Spring bean 的一个片段:

@Component
public class Bean {

    @Value("${bean.timeout:60}")
    private Integer timeout;

    // ...
}

Now I want to test this bean with a JUnit test. I'm therefore using the SpringJUnit4ClassRunnerand the ContextConfigurationannotation.

现在我想用 JUnit 测试来测试这个 bean。因此,我使用SpringJUnit4ClassRunnerContextConfiguration注释。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class BeanTest {

    @Autowired
    private Bean bean;

    // tests ...

    @Configuration
    public static class SpringConfiguration {
        @Bean
        public Bean bean() {
            return new Bean();
        }
    }
}

Unfortunately the SpringJUnit4ClassRunner can't resolve the @Valueexpression, even though a default value is supplied (a NumberFormatExceptionis thrown). It seems that the runner isn't even able to parse the expression.

不幸的是 SpringJUnit4ClassRunner 无法解析@Value表达式,即使提供了默认值(抛出NumberFormatException)。似乎跑步者甚至无法解析表达式。

Is something missing in my test?

我的测试中缺少什么吗?

采纳答案by nobeh

Your test @Configurationclass is missing an instance of PropertyPlaceholderConfigurerand that's why Spring does not know how to resolve those expressions; add a bean like the following to your SpringConfigurationclass

您的测试@Configuration类缺少一个实例,PropertyPlaceholderConfigurer这就是 Spring 不知道如何解析这些表达式的原因;将如下所示的 bean 添加到您的SpringConfiguration类中

@org.springframework.context.annotation.Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ppc.setIgnoreResourceNotFound(true);
    return ppc;
}

and move it to a separate class and use

并将其移动到一个单独的类并使用

@ContextConfiguration(classes=SpringConfiguration.class)

to be more specific when running your test.

在运行测试时更具体。