Spring Boot 테스트에서 다른 application.yml을 로드합니다.
src/main/resources/config/application.yml을 실행하는 스프링 부트 앱을 사용하고 있습니다.
테스트 케이스를 실행할 때:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
public class MyIntTest{
}
테스트 코드는 여전히 application.yml 파일을 실행하여 속성을 로드합니다.테스트 케이스를 실행할 때 다른 *.yml 파일을 실행할 수 있는지 궁금합니다.
한 가지 옵션은 프로파일을 사용하는 것입니다.application-test.yml이라는 파일을 만들고 테스트에 필요한 모든 속성을 해당 파일로 이동한 후@ActiveProfiles'CHANGE: 'CHANGE: 'CHANGE: 'CHANGE:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ActiveProfiles("test") // Like this
public class MyIntTest{
}
application-test.yml이 추가로 로드되므로 application.yml에 있는 모든 속성도 그대로 적용됩니다.이를 원하지 않는 경우 해당 프로파일도 사용하거나 application-test.yml에서 덮어씁니다.
은 '시험 속성'에서 할 수 .src/test/resources/config/application.yml는 Spring Boot에서 .application.yml파일을 테스트 디렉토리에 저장합니다.
config스프링 부츠
설명서에 따르면:
application.properties가 구성 파일 이름으로 적합하지 않은 경우 spring.config.name 환경 속성을 지정하여 다른 파일 이름으로 전환할 수 있습니다.spring.config.location 환경 속성(디렉토리 위치 또는 파일 경로의 쉼표로 구분된 목록)을 사용하여 명시적인 위치를 참조할 수도 있습니다.다음으로 다른 파일명을 지정하는 예를 나타냅니다.
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
경우에도 마찬가지입니다.application.yml
문서:
를 사용하여 다른 속성/yaml 파일을 로드할 수 있습니다.
@TestPropertySource(locations="classpath:test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class MyIntTest{
}
또는 특정 속성/yaml만 덮어쓰려면 다음을 사용할 수 있습니다.
@TestPropertySource(
properties = {
"spring.jpa.hibernate.ddl-auto=validate",
"liquibase.enabled=false"
}
)
이 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」application.yml후하여 테스트 테스트 )에 .src/test/resources/)
그러나 일부 속성을 재정의하거나 추가해야 하는 경우에는 몇 가지 옵션이 있습니다.
1: test 션 11 : 스 optionapplication.ymlsrc/test/resources/config/@The Koju Effect가 그의 답변에서 시사하는 것과 같은 디렉토리.
옵션 2: 프로파일 고유 속성 사용: create sayapplication-test.yml 안에서src/test/resources/「 」:
@ActiveProfiles'CHANGE: 'CHANGE: 'CHANGE: 'CHANGE:@SpringBootTest(classes = Application.class) @ActiveProfiles("test") public class MyIntTest {는른른른른른른른른 or or or or or or or or or를 설정합니다.
spring.profiles.active의@SpringBootTest★★★★@SpringBootTest( properties = ["spring.profiles.active=test"], classes = Application.class, ) public class MyIntTest {
이것은, 에서의 동작뿐만이 아닙니다.@SpringBootTest, 하하와 함께@JsonTest,@JdbcTests,@DataJpaTest및 기타 슬라이스 테스트 주석도 마찬가지입니다.
도 원하는만큼 할 수 있습니다( 「 」 「 」 「 」 「 」 「 」 「 」 「 」 「 」 。spring.profiles.active=dev,hsqldb) - 프로파일에 대한 자세한 내용은 설명서를 참조하십시오.
스프링 부트 프레임워크에서는 .properties 파일 대신 YAML 파일을 제공할 수 있으며 편리합니다.속성 파일의 키는 리소스 폴더의 application.yml 파일에 YAML 형식으로 제공되며 스프링 부트로 자동으로 실행됩니다.값이 올바르게 읽히려면 yaml 형식이 공백을 올바르게 유지해야 합니다.
.@Value("${property}")YAML 파일에서 값을 주입합니다.또한 Spring.active.profiles를 지정하면 환경별로 다른 YAML을 구별하여 쉽게 도입할 수 있습니다.
테스트 목적으로 테스트 YAML 파일은 application-test.yml과 같이 이름을 붙여 테스트 디렉토리의 리소스 폴더에 배치할 수 있습니다.
「 」를하는 는,application-test.yml하시면.yml을 할 수 .@ActiveProfiles('test')주석: 지정한 application-test.yml에서 구성을 가져오도록 스프링을 지정합니다.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationTest.class)
@ActiveProfiles("test")
public class MyTest {
...
}
JUnit 5를 사용하는 경우 @Spring Boot와 같은 다른 주석은 필요하지 않습니다.테스트에 이미 스프링러너 주석이 포함되어 있습니다.별도의 메인 ApplicationTest.class를 유지하면 테스트용 개별 구성 클래스를 제공할 수 있습니다.또한 테스트 메인클래스의 컴포넌트 스캔에서 기본 구성 클래스를 제외함으로써 기본 구성 클래스가 로드되지 않도록 할 수 있습니다.로딩할 프로파일을 제공할 수도 있습니다.
@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
public class ApplicationTest {
public static void main(String[] args) {
SpringApplication.run(ApplicationTest.class, args);
}
}
은 Spring 입니다.YAML YAML을 하는 방법에 링크입니다..properties파일: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
참조: YAML을 사용한Spring @PropertySource
세 번째 답변에는 yaml 값을 매핑하는 별도의 POJO가 있습니다.
@ConfigurationProperties(path="classpath:/appprops.yml", name="db")
public class DbProperties {
private String url;
private String username;
private String password;
...
}
그런 다음 다음과 같이 테스트 클래스에 주석을 추가합니다.
@EnableConfigurationProperties(DbProperties.class)
public class PropertiesUsingService {
@Autowired private DbProperties dbProperties;
}
를 사용한 심플한 작업 구성
@TestProperty소스 및 속성
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {"spring.config.location=classpath:another.yml"})
public class TestClass {
@Test
public void someTest() {
}
}
Spring 4.1부터는 @TestPropertySource 주석을 사용하여 application.yml에서 속성을 직접 설정할 수 있습니다.
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = {"yoursection.yourparameter=your_value"})
public MyIntTest
{
//your test methods
}
yaml 매개 변수를 완전한 속성 구조로 변환하기만 하면 됩니다.예를 들어 다음과 같습니다.application.yml의 내용은 다음과 같습니다.
yoursection:
yourparameter:your_value
다음으로 @TestPropertySource 내에 들어가는 값은 다음과 같습니다.
yoursection.yourparameter=your_value
이는 옵션 중 하나로 간주될 수 있습니다.yml 파일을 로드하고 싶은 경우(위 주석을 적용했을 때 기본적으로 로드되지 않음) 요령은 다음과 같습니다.
@ContextConfiguration(classes= {...}, initializers={ConfigFileApplicationContextInitializer.class})
여기 샘플 코드가 있습니다.
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(classes= {DataSourceTestConfig.class}, initializers = {ConfigFileApplicationContextInitializer.class})
public class CustomDateDeserializerTest {
private ObjectMapper objMapper;
@Before
public void setUp() {
objMapper = new ObjectMapper();
}
@Test
public void test_dateDeserialization() {
}
}
setup config java 파일이 여기에 있는지 다시 확인합니다.DataSourceTestConfig.java에는 다음 속성 값이 포함되어 있습니다.
@Configuration
@ActiveProfiles("test")
@TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })
public class DataSourceTestConfig implements EnvironmentAware {
private Environment env;
@Bean
@Profile("test")
public DataSource testDs() {
HikariDataSource ds = new HikariDataSource();
boolean isAutoCommitEnabled = env.getProperty("spring.datasource.hikari.auto-commit") != null ? Boolean.parseBoolean(env.getProperty("spring.datasource.hikari.auto-commit")):false;
ds.setAutoCommit(isAutoCommitEnabled);
// Connection test query is for legacy connections
//ds.setConnectionInitSql(env.getProperty("spring.datasource.hikari.connection-test-query"));
ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
long timeout = env.getProperty("spring.datasource.hikari.idleTimeout") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.idleTimeout")): 40000;
ds.setIdleTimeout(timeout);
long maxLifeTime = env.getProperty("spring.datasource.hikari.maxLifetime") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.maxLifetime")): 1800000 ;
ds.setMaxLifetime(maxLifeTime);
ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
int poolSize = env.getProperty("spring.datasource.hikari.maximum-pool-size") != null ? Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")): 10;
ds.setMaximumPoolSize(poolSize);
return ds;
}
@Bean
@Profile("test")
public JdbcTemplate testJdbctemplate() {
return new JdbcTemplate(testDs());
}
@Bean
@Profile("test")
public NamedParameterJdbcTemplate testNamedTemplate() {
return new NamedParameterJdbcTemplate(testDs());
}
@Override
public void setEnvironment(Environment environment) {
// TODO Auto-generated method stub
this.env = environment;
}
}
Lu55 옵션1 방법...
별도의 리소스 폴더에 테스트 전용 application.yml을 추가합니다.
----메인자바│--리소스응용 프로그램.yml§--테스트----자바§--리소스application.yml
이 프로젝트 구조에서는 메인 아래의 application.yml이 로드되며, 메인 아래의 코드가 실행 중일 경우 테스트 중인 application.yml이 테스트에서 사용됩니다.
이 구조를 설정하려면 새 패키지 폴더 테스트/리소스가 없는 경우 추가하십시오.
Eclipse 프로젝트 우클릭 -> Properties -> Java Build Path -> Source Tab -> (리그사이드 대화 상자) "Add Folder..."
[소스 폴더 선택] -> [마크 테스트] -> [새로운 폴더 작성...]버튼을 클릭합니다.-> [ Textfeld ]에 [리소스]를 입력합니다.-> [종료]버튼을 클릭합니다.
Finish 버튼을 누르면 소스 폴더 {projectname}/src/test/recources(신규)가 표시됩니다.
옵션:프로젝트 탐색기 보기의 폴더 순서를 정렬합니다.[ Order and Export ]탭의 [Klick]를 클릭하여 {projectname}/src/test/recources를 맨 아래로 이동합니다.적용 후 닫기
프로젝트 정리!!!
이클립스 -> 프로젝트 -> 청소...
이제 테스트용과 메인 어플리케이션용 분리된 참말이 있습니다.
@IlyaSerbis answer를 테스트해 본 결과, 정상적으로 동작하고 있습니다.Spring Boot 2.3을 사용하고 있습니다.
나는 이 시나리오들을 테스트했고 효과가 있었다.
시나리오 1 - 처음 작성application.ymljUnit의 목적을 위해 그것을 아래에 둡니다.src/test/resources/config(어플리케이션.yml), yaml(어플리케이션.yml), yaml(어플리케이션.yml), yaml(어플리케이션.yml)입니다., ,, 에, 에, 에, 에, 에, that, that, 습, 습, that, that, that, that, that, that, that, that, that, that, that, that, that, that, that that, , ,application.ymlsrc/main/resources/config이치노
주의: 입력Scenario1application.yml application.yml 。 ifsrc/main/resources/config/application.ymlsrc/test/resources/config/application.yml.src/main/resources/application.ymlsrc/test/resources/application.yml
시나리오2 - 그 후 작성했습니다.application-test.ymlapplication.yml아래src/test/resources/config and and를 합니다.@ActiveProfiles("test")이 jUnit에서 을 알 수 있었습니다.application-test.yml(Overwrite))application.yml공통 속성의 경우)를 사용하여 값을 가져옵니다.application.yml에 되어 있지 않은 입니다.application-test.yml.
@Spring Boot 사용 가능src\main\java\com에서 yml 파일을 로드하는 주석을 테스트합니다.따라서 유닛 테스트를 실행하면 모든 속성이 config properties 클래스에 이미 존재합니다.
@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressFieldsTest {
@InjectMocks
AddressFieldsValidator addressFieldsValidator;
@Autowired
AddressFieldsConfig addressFieldsConfig;
...........
@Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(addressFieldsValidator,"addressFieldsConfig", addressFieldsConfig);
}
}
설정이 적은 경우 @Value 주석을 사용할 수 있습니다.설정 속성 클래스를 사용할 수도 있습니다.예:
@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "address.fields.regex")
public class AddressFieldsConfig {
private int firstName;
private int lastName;
.........
언급URL : https://stackoverflow.com/questions/38711871/load-different-application-yml-in-springboot-test
'programing' 카테고리의 다른 글
| TypeScript 사용자 지정 오류 클래스 (0) | 2023.04.06 |
|---|---|
| iOS 8/Safari 8은 ASP에서 작동하지 않습니다.NET AJAX 확장 (0) | 2023.04.06 |
| 1개의 CDN 또는 여러 개의 CDNS에서 파일 로드 (0) | 2023.04.06 |
| Angular가 자동으로 'ng-invalid' 클래스를 '필수' 필드에 추가하고 있습니다. (0) | 2023.04.06 |
| Gravity Forms - 현재 페이지 번호 가져오기 (0) | 2023.04.06 |