Je veux passer un test Junit pour le printemps-boot comme ci-dessous:@Value fonctionne pas sur Spring Boot test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationTest.class})
public class TestOnSpring {
@Value("${app.name}")
private String appName;
@Test
public void testValue(){
System.out.println(appName);
}
}
et ApplicationTest.java comme celui-ci
@ComponentScan("org.nerve.jiepu")
@EnableAutoConfiguration()
public class ApplicationTest {
public static void main(String[] args) {
SpringApplication.run(ApplicationTest.class, args);
}
}
et mon POM comme celui-ci :
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.BUILD-SNAPSHOT</version>
</parent>
Quand je lance le test, je suis arrivé ci-dessous des informations d'erreur
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
Mais quand je lance cette application comme Java normale d'application
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
Il fonctionne bien!
Qu'est-ce qui ne va pas? Comment devrais-je passer le test de junit avec Spring-boot? Merci beaucoup!
Vous exécutez votre cas de test incorrect. Vous utilisez Spring Boot puis utilisez la méthode de test appropriée. Au lieu de 'ContextConfiguration', utilisez' SpringApplicationConfiguration'. –