@Value 春季启动测试中的“无法解析占位符”

2022-08-31 20:53:22

我想对Spring-boot进行Junit测试,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationTest.class})
public class TestOnSpring {
    @Value("${app.name}")
    private String appName;

    @Test
    public void testValue(){
        System.out.println(appName);
    }
}

和 ApplicationTest.java像这样

@ComponentScan("org.nerve.jiepu")
@EnableAutoConfiguration()
public class ApplicationTest {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationTest.class, args);
    }
}

和我的POM像这样:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.BUILD-SNAPSHOT</version>
    </parent>

当我运行测试时,我得到了下面的错误信息

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'app.name' in string value "${app.name}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:172)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:807)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1027)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
    ... 31 more

但是当我像普通的Java应用程序一样运行这个应用程序时

@SpringBootApplication
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}

它工作得很好!

这是怎么回事?我应该如何使用Spring-boot进行junit测试?多谢!


答案 1

您需要添加

@PropertySource(“类路径:应用程序.属性”)

到你的类,所以它会选择你的正常配置。

如果需要不同的配置进行测试,可以添加

@TestPropertySource(locations=“classpath:test.properties”)

如果不是只是复制粘贴您的配置文件到文件夹,那么boot将从那里选择。test/resources

请参阅此内容


答案 2

您可以使用自动创建的。@SpringBootTestPropertySourcesPlaceholderConfigurer

这在 Spring Boot 文档的测试一章中进行了描述。

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-configfileapplicationcontextinitializer-test-utility


推荐