봄 테스트용으로 메모리 데이터베이스에 특정 구성
유닛 테스트를 실행할 때는 H2/HSQL 등의 메모리 내 데이터베이스를 사용하지만 Spring Boot 어플리케이션을 실행할 때는 실제 가동 데이터베이스를 사용하도록 Spring Boot 어플리케이션을 설정하는 방법 [Postgre/My]SQL]?
여기에는 스프링 프로파일을 사용할 수 있습니다.구체적인 방법은 다음과 같습니다.
환경별 속성 파일:
application.properties:
spring.profiles.active: dev
application-dev.properties
spring.jpa.database: MYSQL
spring.jpa.hibernate.ddl-auto: update
spring.datasource.url: jdbc:mysql://localhost:3306/dbname
spring.datasource.username: username
spring.datasource.password: password
application-test.properties
spring.jpa.database: HSQL
MySQL 드라이버와 H2 드라이버 모두 탑재pom.xml
, 다음과 같이 합니다.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
마지막으로 테스트 클래스에 주석을 붙입니다.@ActiveProfiles("test")
.
또 다른 접근법은 주석을 추가하는 것이다.@AutoConfigureTestDatabase
시험수업입니다.테스트는 보통 다음과 같습니다.
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
public class MyRepositoryTest {
@Autowired
MyRepository repository;
@Test
public void test() throws Exception {
// Tests...
}
}
임베디드 데이터베이스 의존성을 pom.xml 파일에 추가해야 합니다.임베디드 데이터베이스의 경우 이 주석은 pom 파일에 종속성만 추가되어도 동작하지 않습니다.
@Spring Boot 사용 시테스트 마법, 다음 두 가지 변경 사항만 수행하면 됩니다.
- pom.xml에 'h2' 테스트 종속성 추가
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
@RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) @AutoConfigureTestDatabase public class SpringBootTest{ @Autowired private RequestRepository requestRepository; }
테스트에 사용된 모든 spring jpa bean/repository는 h2를 백업 데이터베이스로 사용합니다.
2019-04-26 13:13:34.198 INFO 28627 --- [ main ] bedded Data Source Bean Factory Post Processor : 'Data Source' Data Source bean을 임베디드 버전으로 대체
2019-04-26 13:13:34.199 INFO 28627 --- [ main ]o.s.b.f.s.DefaultListableBeanFactory : 콩 '데이터 원본'에 대한 콩 정의를 재정의하고 있습니다.
2019-04-26 13:13:36.194 INFO 28627 --- [ main ] os.s.j.d.e.EmbeddedDatabaseFactory : url='jdbc:h2:mem:2784768e-f053-4bb3-edda34956893;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false',username='sa'를 시작하는 중입니다.
주의: 'application.properties'에 정의된 'spring-jpa' 속성이 아직 있으며 프로파일을 사용하지 않습니다.@AutoConfigureTestDatabase는 테스트 기본값인 AutoConfigureTestDatabase로 기존 jpa 구성을 덮어씁니다.교체하다.
가장 심플한 솔루션:
1) src/main/main에 application.properties(실가동 구성):
spring.datasource.url=jdbc:mysql://localhost:3306/somedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
및 application-test.properties를 HSQL 구성으로 설정합니다.
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.database = HSQL
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
spring.datasource.driverClassName = org.hsqldb.jdbcDriver
spring.datasource.url= jdbc:hsqldb:mem:scratchdb
spring.datasource.username = sa
spring.datasource.password =
2) pom.xml에 HSQL 의존관계가 없는 경우 추가합니다.
3) @ActiveProfiles("test")를 사용하여 테스트 클래스에 주석을 추가합니다.
내 경우엔 아주 잘 작동했어
@산제이넌 그냥 한 개만 가져도 돼production
다음과 같은 프로파일을 사용할 수 있습니다.
spring.jpa.hibernate.ddl-auto: update
spring.datasource.url: jdbc:mysql://localhost:3306/dbname
spring.datasource.username: username
spring.datasource.password: password
이치노 삽입형 test
스코프는 테스트에서 사용할 수 있습니다.(커스터마이제이션 하여 테스트를 되지 않습니다는 「」에 보존되어 있기 때문입니다).production
프로파일)을 참조해 주세요.이 경우 임베디드 데이터베이스를 검색하여 시작합니다.더 " " " 를 할 수 있습니다.application-test.properties
.ActiveProfiles("test")
테스트에 접속합니다.
: 플플 with with로 :maven
: 배치만 하면 됩니다.application.properties
src/test/resources
이치노
스프링(부트) 프로파일 메커니즘은 매우 강력한 도구이며, 범위에서는 "테스트 시간과 실행 시간 사이의 설정 스왑"을 훨씬 능가합니다.분명히 설명했듯이, 이것도 할 수 있습니다.
이 솔루션은 개발 및 테스트에 대한 공통 설정을 가능하게 합니다.이 솔루션을 기반으로 합니다.Junit 테스트에서 기본 Spring-Boot application.properties 설정을 덮어씁니다.
- src/main/main/application.properties의 application.properties
#common settings for DEVELOPMENT and TEST:
......
......
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:postgresql://localhost:5432/databasename
spring.datasource.username=postgres
spring.datasource.password=somepassword
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = none
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
- test.properties(src/main/main/application.properties)는 application.properties에 속성을 덮어쓰고 추가합니다.
spring.datasource.url=jdbc:h2:mem:testdb;MODE=PostgreSQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=false
- H2 및 Postgre 데이터베이스의 pom.xml 설정
<!-- h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- postgress -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
- 테스트 수업 중:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
public class ModelTest {
}
아래 모듈을 탑재한 멀티모듈 Gradle Spring Boot 어플리케이션을 사용하고 있다.
- employeemanager App - Spring Application 메인 클래스 위치
- employeemanager IntTests - 오이 테스트 장소
어플리케이션 부팅 시 MySQL DB를 사용하고 Oy Integration 테스트 시 H2를 사용해야 했습니다.
솔루션:src/main/resources i에 의해 semployemanager App 모듈에서 다음과 같은 내용의 application.properties가 배치되었습니다.
#My SQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/employeemanager
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
또한 Integration Test Module (employemanagerIntTests) src/test/Resources에서 다음 내용으로 application.properties를 배치했습니다.
#H2 In-Memory DB Configuration
spring.datasource.url=jdbc:h2://mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.format_sql=true
그리고 스텝 정의 수업에서 나는 이러한 주석만 추가했다.
@CucumberContextConfiguration
@SpringBootTest(classes = SpringBootApplicationMainClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
build.gradle 파일에서 H2 종속성을 추가했습니다.
testImplementation 'com.h2database:h2:1.4.200'
따라서 테스트를 실행했을 때 H2가 활성화되어 Create, Update, Read 및 Delete를 사용한 모든 테스트가 성공했습니다.
언급URL : https://stackoverflow.com/questions/32001391/configure-specific-in-memory-database-for-testing-purpose-in-spring
'programing' 카테고리의 다른 글
리액트 + 플럭스 및 서버 측 렌더링(이형 반응 + 플럭스) (0) | 2023.03.23 |
---|---|
Angular에서 상위 범위 변수 업데이트JS (0) | 2023.03.18 |
리액트 기능 컴포넌트의 lodash debouncomponent (0) | 2023.03.18 |
React를 위한 부트스트랩과 머티리얼 UI의 비교 (0) | 2023.03.18 |
ng-cloak 디렉티브를 올바르게 사용하는 방법 (0) | 2023.03.18 |