Junit 테스트에서 기본 Spring-Boot application.properties 설정을 덮어씁니다.
이 Spring-Boot으로 설정되어 있습니다.application.properties
( src / main / filength / application . properties ) 。
을 JUnit에서 .test.properties
/ / . properties 일 file ( src / test / test . properties )
Junit 테스트 전용 Config 클래스가 있습니다.
package foo.bar.test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {
}
에 음에 i i i i를 @PropertySource("classpath:test.properties")
TestConfig 클래스에서는 문제가 없지만 이러한 속성은 application.properties 설정을 덮어쓰지 않습니다(Spring-Boot Reference Doc-23 참조). 외부 설정).
나서 나는 ★★★★★★★★★★★★★★★★★★★★★★★를 사용해 보았다.-Dspring.config.location=classpath:test.properties
테스트를 호출할 때 사용합니다.성공했지만 각 테스트 실행에 대해 이 시스템 속성을 설정하지 않습니다..
@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {
static {
System.setProperty("spring.config.location", "classpath:test.properties");
}
}
불행히도 다시 성공하지 못했습니다.
를 어떻게 덮어쓸 것인가에 합니다.application.properties
test.properties
내가 간과한 게 틀림없어
하시면 됩니다.@TestPropertySource
을 application.properties
: . javadoc :: :
테스트 속성 소스를 사용하여 시스템 및 애플리케이션 속성 소스에 정의된 속성을 선택적으로 재정의할 수 있습니다.
예를 들어 다음과 같습니다.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class ExampleApplicationTests {
}
Boot는 으로 로딩됩니다.src/test/resources/application.properties
하는 경우, adnotations를 사용합니다.
@RunWith(SpringRunner.class)
@SpringBootTest
이름을 바꾸세요.test.properties
로로 합니다.application.properties
자동 설정을 이용합니다.
(환경에) 속성 파일만 로드하면 되는 경우, 여기에 설명된 대로 다음을 사용할 수도 있습니다.
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
[갱신: 테스트 대상 특정 속성 덮어쓰기]
src/main/resources/application-test.properties
.- 클래스에서 "Atest 에는 「」를 붙입니다.
@ActiveProfiles("test")
.
은 로딩됩니다.application.properties
그 다음에 application-test.properties
여기서 정의한 규칙에 따라 속성을 테스트 케이스의 애플리케이션 컨텍스트에 넣습니다.
데모 - https://github.com/mohnish82/so-spring-boot-testprops
메타 주석을 사용하여 설정을 외부화할 수도 있습니다.예를 들어 다음과 같습니다.
@RunWith(SpringJUnit4ClassRunner.class)
@DefaultTestAnnotations
public class ExampleApplicationTests {
...
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public @interface DefaultTestAnnotations { }
한 또 다른 하는 경우)@SpringBootTest
★★★★
@SpringBootTest(properties = {"propA=valueA", "propB=valueB"})
, , 같은 것을 가지고 있습니다.application.properties
src/main/resources
★★★★★★★★★★★★★★★★★」src/test/resources
그리고 당신은 왜 그 이유를 궁금해하는지 궁금해하고 있습니다.application.properties
테스트 폴더는, 이 폴더보다 우선하지 않습니다.application.properties
주요 자료에서 계속 읽어보십시오.
간단한 설명:
「 」가 application.properties
아래src/main/resources
같은 「」application.properties
아래src/test/resources
,어떤.application.properties
는 테스트를 실행하는 방법에 따라 선택됩니다.폴더 구조 src/main/resources
그리고.src/test/resources
는 Maven 아키텍처 컨벤션입니다.따라서 테스트를 실행하면mvnw test
또는 심지어gradlew test
,그application.properties
에src/test/resources
test classpath가 main classpath보다 우선하므로 픽업됩니다.하지만 만약 당신이 당신의 테스트를Run as JUnit Test
이클립스/STS에서는application.properties
에src/main/resources
메인 클래스 패스가 test classpath보다 우선하므로 픽업됩니다.
메뉴바를 열면 확인하실 수 있습니다. Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line"
.
다음과 같은 것이 표시됩니다.
XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 클래스 패스
XXX\workspace-spring-tool-suite-4-4.5.1.릴리즈\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;
classpath xxx\main이 첫 번째이고 그 다음에 xxx\test가 표시됩니다.네, 모두 클래스 패스에 관한 것입니다. :-)
사이드 노트:실행 구성에서 재정의된 속성(예: Spring Tool Suite IDE)은 application.properties보다 우선합니다.
순서를 변경합니다.
이제 봄에는 모든 것을 구성할 수 있습니다.빌드 클래스 경로를 변경하여 xxx\test를 먼저 실행하고 xxx\main을 차례로 실행하도록 할 수 있습니다.
에간 to 로 가면 돼요.Project > Properties > Java Build Path > Order and Export
다음과 같은 테스트 폴더를 먼저 배치하여 빌드 클래스 경로 순서를 변경합니다.
바로 그거야!
뛰어난 솔루션
시험할 때은 ᄃ, ́, ́, ́, ́, ́, ́, ́, ́, ́, ́, ́, ́를 활성화하는 것입니다.src/test/resources/application-{profile}.properties
서 (어디서)profile
테스트 가능)의 예를 들어 다음과 같습니다.src/main/resources/application.properties
:
spring.disc.active=테스트
이는 보다 깔끔하며 무엇을 수행할 때 활성화할 프로파일을 완벽하게 제어할 수 있습니다.
TLDR:
가 한 있는 입니다.src/main/resources/application.properties
, 「」라고 하는 것도 있습니다.src/test/resources/application-default.properties
모든 테스트에 대한 일부 설정을 덮어씁니다.
전력 개발자의 경우:
봄 을 변경 중인 봄/봄 프로파일을 가지고 .application-default.yaml
이치노이 파일은 커밋되어 있지 않기 때문에 각 개발자가 작업 중인 프로파일과 니즈(기능 등)를 활성화하는 방법을 선택할 수 있습니다.
spring:
profiles:
include:
- local
- devlocal
- wip
# - kafka@docker
---
spring.profiles: wip
# ... overriding properties
전체적인 이야기
저도 같은 문제에 부딪혀 지금까지 프로필을 사용하지 않았습니다.지금 해야 하는 일이 귀찮아 보였고, 쉽게 잊어버릴 수 있는 프로파일 발표를 기억했습니다.
고유의 「」를 요령입니다.application-<profile>.properties
는 일반 프로파일의 설정을 덮어씁니다.https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties 를 참조해 주세요.
Spring 5.2.5 및 Spring Boot 2.2.6을 사용하고 있으며 파일 전체가 아닌 일부 속성만 덮어쓰려는 경우.새로운 주석 @DynamicPropertySource 를 사용할 수 있습니다.
@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
@DynamicPropertySource
static void neo4jProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
}
}
I just configured min as the following :
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# changing the name of my data base for testing
spring.datasource.url= jdbc:h2:mem:mockedDB
spring.datasource.username=sa
spring.datasource.password=sa
# in testing i don`t need to know the port
#Feature that determines what happens when no accessors are found for a type
#(and there are no annotations to indicate it is meant to be serialized).
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false`enter code here`
않으면 컨피규레이터할 수 .spring.config.name=test
자원 「클래스 패스」를 취득합니다.src/test/test.properties
의 예org.springframework.boot.SpringApplication
는 이 된 test됩니다.「 test . properties 」 will 、 「 test.properties 」입니다.
이점: 테스트 자동 설정
단점: C에서 "spring.config.name" 속성이 노출됩니다.I. 레이어
참조: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
spring.config.name=application # 설정 파일명
이것도 사용할 수 있을 것 같습니다.
@TestPropertySource(properties = "spring.config.additional-location=classpath:application-test.yml")
spring.config.communal-location을 사용하여 커스텀 설정 위치를 설정할 경우 기본 위치 외에 이러한 위치가 사용됩니다.
파일이 우선됩니다.
자세한 것은 이쪽을 참조해 주세요.
META-INF로 할 수 PostProcessor src/test/META-INF로 할 수 .factors는 src/test/java 환경프로세서 구현입니다.
spring.factories
# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
com.example.test.YourTestPropertiesConfig
YourTestPropertiesConfig.java
package com.example.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import java.util.HashMap;
import java.util.Map;
public class YourTestPropertiesConfig implements EnvironmentPostProcessor {
private static final Map<String, Object> testProperties = new HashMap<>();
private static final Set<String> testPropertiesFile = new HashSet<>();
static {
//Add the properties you need to take effect globally in the test directly here.
testProperties.put("spring.jackson.time-zone", "GMT");
testPropertiesFile.add("classpath:test.properties");
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
environment.getPropertySources().addFirst(new MapPropertySource("TestProperties", testProperties));
for (String location : testPropertiesFile) {
try {
environment.getPropertySources().addFirst(new ResourcePropertySource(location));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void addProperty(String key, Object value) {
testProperties.put(key, value);
}
public static void addProperty(String location) {
testPropertiesFile.add(location);
}
}
JUnit이 기록되는 src/test/resources에 application.properties 파일을 생성할 수도 있습니다.
언급URL : https://stackoverflow.com/questions/29669393/override-default-spring-boot-application-properties-settings-in-junit-test
'itsource' 카테고리의 다른 글
VueJs, 계산된 자산과 감시자의 차이점? (0) | 2022.08.14 |
---|---|
Rubaxa-Sortable이 'Element'에서 'matches'를 실행하지 못했습니다. '>*'는 올바른 선택기가 아닙니다. (0) | 2022.08.14 |
Java에서의 콜백 함수 (0) | 2022.08.14 |
정적 컨텍스트에서 리소스 컨텐츠를 가져오려면 어떻게 해야 합니까? (0) | 2022.08.14 |
Vue.js: 조건부 클래스 스타일 바인딩 (0) | 2022.08.14 |