programing

'application.yml'의 스프링 부트 속성이 JUnit 테스트에서 로드되지 않습니다.

newnotes 2023. 3. 21. 22:33
반응형

'application.yml'의 스프링 부트 속성이 JUnit 테스트에서 로드되지 않습니다.

내가 뭘 잘못하고 있지?이 작은 독립 실행형 앱을 사용하고 있습니다. 이 앱을 실행하면src/main/resources/config/application.ymlJUnit 에서는 같은 설정이 동작하지 않습니다.아래를 참조해 주세요.

@Configuration
@ComponentScan
@EnableConfigurationProperties

public class TestApplication {

    public static void main(String[] args) {

        SpringApplication.run(TestApplication.class);
    }
}


@Component
@ConfigurationProperties

public class Bean{
    ...
}

다음 기능은 작동하지 않습니다.속성과 동일합니다.application.yml로딩되지 않았습니다.Bean가지고 있는 것은null값:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)

public class SomeTestClass {
    ...
}

이것을 시험해 보세요.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestApplication.class, 
    initializers = ConfigFileApplicationContextInitializer.class)
public class SomeTestClass {
    ...
}

편집:

Spring Boot 버전 1.5 이상의 경우SpringApplicationConfiguration을 위해 제거되었다SpringBootTest또는 직접 사용SpringBootContextLoader.

아직 사용할 수 있습니다.initializers매개 변수ContextConfiguration주석입니다.

를 사용하여 SpringBoot 2.0에서 커스텀 yml 파일을 로드하는 방법@SpringBootTest

  • test\syslog에서 yml 파일을 만듭니다.
  • 사용하다ConfigFileApplicationContextInitializer그리고.spring.config.location소유물

코드 예:

@RunWith(SpringRunner.class)
@ContextConfiguration(
    classes = { MyConfiguration.class, AnotherDependancy.class },
    initializers = {ConfigFileApplicationContextInitializer.class} )
@TestPropertySource(properties = { "spring.config.location=classpath:myApp-test.yml" })
public class ConfigProviderTest {
    @Autowired
    private MyConfiguration myConfiguration; //this will be filled with myApp-test.yml 

   @Value("${my.config-yml-string}")
   private String someSrting; //will get value from the yml file.

}

JUnit 5의 경우@ExtendWith(SpringExtension.class)대신 주석@RunWith(SpringRunner.class)

2017년 2월 대안:

@SpringBootTest
@ContextConfiguration(classes = { TestApplication.class })
@RunWith(SpringRunner.class)
public class SomeTestClass {
   ...
}

(와 함께) 군살 없는 변종@SpringBootTest):

@ContextConfiguration(classes = { TestApplication.class },
                 initializers = { ConfigFileApplicationContextInitializer.class })
@RunWith(SpringRunner.class)
public class SomeTestClass {

다른 방법이 있습니다.[스프링 부트 v1.4.x]

@Configuration
@ConfigurationProperties(prefix = "own")
public class OwnSettings {

    private String name;
    Getter & setters...

}

import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@BootstrapWith(SpringBootTestContextBootstrapper.class)
public class OwnSettingsTest {

  @Autowired
  private OwnSettings bean;

  @Test
  public void test() {
    bean.getName();
  }
}

이 작업은 'application.properties' 파일도 존재하는 경우에만 작동합니다.

예: 메이븐 프로젝트:

src/main/resources/application.properties [파일은 비워둘있지만 필수입니다]
src/main/main/application.yml [실제 설정 파일입니다]

스프링 부트 2를 사용한 유닛 테스트

spring boot 2는 디폴트로 application.properties를 지원합니다.application.yml에 대해서는 아래에 추가합니다.

@TestPropertySource(properties = { "spring.config.location=classpath:application.yml" })

예.

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "spring.config.location=classpath:application.yml" })
public class ServiceTest {...}

Liam의 답변덧붙여, 대안은 다음과 같습니다.

@TestPropertySource(locations = { "classpath:application.yaml" })

여기서 중요한 차이점은 테스트가 실패하여 파일을 찾을 수 없는 예외가 발생한다는 것입니다.application.yaml에 없습니다./test/resources디렉토리

스프링 부트 버전 2.6.0 이후org.springframework.boot.test.context.ConfigFileApplicationContextInitializer권장되지 않으며 대신 를 사용하는 것이 좋습니다.org.springframework.boot.test.context.ConfigDataApplicationContextInitializer.

테스트에서는 다음과 같이 사용할 수 있습니다.

@ContextConfiguration(classes = {
  ...        
}, initializers = ConfigDataApplicationContextInitializer.class)
public class MyTestingClassIT

스프링 부트 2의 예:

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withInitializer(new ConfigFileApplicationContextInitializer());

@Test public void test() throws Exception {

    this.contextRunner
    .withUserConfiguration(TestApplication.class)
    .run((context) -> {

        .....

    });
}

리암의 대답연장하다

추가할 수 있습니다.spring.config.additional-location=classpath:application-overrides.yaml기본 위치의 Configuration이 제공된 추가 Configuration과 병합됩니다.

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = {
  "spring.config.additional-location=classpath:testcases/test-case-properties.yaml",
})
public class SpecificTestCaseIntegrationTest {

내 경우, 나는 도서관을 테스트하려고 했다.@SpringBootApp일반 앱 클래스 경로에서 선언되었지만 테스트 컨텍스트에 하나 있습니다.Spring Boot 초기화 프로세스를 디버깅한 후 Spring Boot의 YamlPropertySourceLoader(1.5.2 현재)를 발견했습니다.RELEASE)는 다음 경우를 제외하고 YAML 속성을 로드하지 않습니다.org.yaml.snakeyaml.Yaml클래스 패스에 있습니다.해결방법은 POM에 snakyaml을 테스트 의존관계로 추가하는 것이었습니다.

    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.19</version>
        <scope>test</scope>
    </dependency>

이것은 동작합니다.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {

    @Test
    public void contextLoads() {
    }

}

언급URL : https://stackoverflow.com/questions/33213854/spring-boot-properties-in-application-yml-not-loading-from-junit-test

반응형