在Spring Boot测试中@Value“无法解析占位符”

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

回答:

您需要添加

@PropertySource(“ classpath:application.properties”)

上课,这样它将选择您的常规配置。

如果您需要其他配置进行测试,则可以添加

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

test/resources ,那么启动将从那里选择。

以上是 在Spring Boot测试中@Value“无法解析占位符” 的全部内容, 来源链接: utcz.com/qa/427405.html

回到顶部