programing

@Spring Boot Test에서의 값 "플레이스 홀더를 해결할 수 없습니다"

sourcejob 2023. 4. 4. 21:14
반응형

@Spring Boot Test에서의 값 "플레이스 홀더를 해결할 수 없습니다"

다음과 같이 스프링 부트에 대한 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);
    }
}

잘 된다!

무슨 문제라도 있습니까?스프링 부트로 junit 테스트를 받는 방법은 무엇입니까?정말 고마워.

를 추가해야 합니다.

@PropertySource("classpath: application.properties")

일반 구성을 선택할 수 있습니다.

테스트를 위해 다른 구성이 필요한 경우 다음을 추가할 수 있습니다.

@TestPropertySource(locations="classpath: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

테스트 클래스에 주석을 달았습니다.@ContextConfiguration(classes = {ApplicationTest.class}).어디서ApplicationTest.class는, 전술한 패키지에서 컴포넌트를 스캔 합니다.테스트를 실행하면 리소스 폴더에서 'test'가 아닌 'main'으로 구성을 검색합니다.클래스에 주석을 다는 경우@SpringBootTest(classes = {ClassToBeTested.class})아니면 그냥@SpringBootTest이 경우에는 (100% 확실하지 않은) 제한된 컨텍스트를 생성하여 테스트/리소스에서 속성을 얻을 수 있다고 생각합니다.

속성이 테스트에 고유한 경우 속성/yml 파일의 이름을 다음과 같이 지정할 수 있습니다.application-test.properties또는application-test.yml. 및 사용하다@ActiveProfiles("test")항상 테스트별 속성 파일을 읽을 수 있도록 합니다.

저는 보통 이 솔루션을 저에게 맞는 방법으로 사용하고 있습니다.

이 문제는 애플리케이션 속성에 대한 프로파일 세트와 관련이 있었습니다.

application.yml:

spring:
  config:
    activate:
      on-profile: local
mongodb:
  uri: mongodb+srv:/

값을 참조하는 클래스:

@Value("${mongodb.uri}")
private String uri;

테스트 클래스 방법의 분해능:

@SpringBootTest
@ActiveProfiles("local")
class myTestClass {

언급URL : https://stackoverflow.com/questions/33256702/value-could-not-resolve-placeholder-in-spring-boot-test

반응형