@Value不适用于Spring Boot Test

我想对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是这样的:

  org.springframework.boot spring-boot-starter-parent 1.3.0.BUILD-SNAPSHOT  

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

 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测试? 非常感谢!

你需要添加

@PropertySource( “类路径:application.properties”)

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

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

@TestPropertySource(位置= “类路径:test.properties”)

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

看到这个 。

您可以使用@SpringBootTest自动创建PropertySourcesPlaceholderConfigurer

这在Spring Boot文档的测试章节中有所描述。

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