REST API(10) 테스트용 DB 설정 분리하기
테스트용 DB(H2) / 애플리케이션용 DB(PostgreSQL)
테스트 할 때는 계속 H2를 사용해도 좋지만 애플리케이션 서버를 실행할 때 PostgreSQL을 사용하도록 변경하자.
구현 Package 및 Class
Docker 설치
우선 Docker를 설치해 주었다.
PostgreSQL 컨테이너 실행
도커로 PostgreSQL 컨테이너를 실행하기 위한 명령어이다.
1
$ docker run --name rest -p 5432:5432 -e POSTGRES_PASSWORD=pass -d postgres
rest
를 컨테이너 이름으로 하여, -p
옵션으로 port 매핑, -e
옵션으로 환경변수 설정, -d
로 데몬 모드로 설정했다.
$ docker ps
명령어를 입력하면 컨테이너 목록에서 rest 컨테이너를 확인할 수 있다.
도커 컨테이너에 들어가기
다음은 도커 컨테이너에 들어가기 위한 명령어이다.
1
2
3
4
5
$ docker exec -i -t rest bash # target 컨테이너를 rest 로 지정
$ su - postgres # postgres로 user 변경
$ psql -d postgres -U postgres
$ \l # 데이터베이스 목록 확인
$ \dt # 테이블 확인
DB 설정 분리하기
이제 테스트용 DB는 H2로, 애플리케이션용 DB는 PostgreSQL로 분리하는 작업을 해보겠다.
H2 DB Test scope으로 변경
test에서 H2 Database를 사용하기 위해 pom.xml에서 h2database를 test scope으로 변경해야 한다.
1
2
3
4
5
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
application.properties
데이터소스와 하이버네이트 설정을 위해 applicaion.properties 에 다음 내용을 추가한다.
하이버네이트 설정을 통해 이벤트에 대한 테이블을 만들어 줄 수 있고, 우리가 쿼리가 볼 수 있도록 할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
spring.jackson.deserialization.fail-on-unknown-properties=true
spring.datasource.username=postgres
spring.datasource.password=pass
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
application-test.properties
테스트에서 H2 Database를 사용하기 위해서는 테스트에 대한 application.properties
가 필요하다.
test
안에 resources
디렉토리를 생성하여 설정 파일(application.properties)을 추가해준다.
하지만 이럴 경우 애플리케이션 설정과 테스트 설정이 중복된다.
따라서, 이를 해결하기 위해 테스트 설정 파일의 이름을 application-test.properties
로 변경하고,
내용을 다음과 같이 변경하여 오버라이딩 하고 싶은 것만 남긴다.
EventControllerTests 수정
테스트에서 이 설정을 사용할 수 있도록 EventControllerTests
에 @ActiveProfiles("test")
어노테이션을 추가하면 애플리케이션 설정과 테스트 설정 중복을 피할 수 있게 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// import 생략
import org.springframework.test.context.ActiveProfiles; // 추가
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestDocs
@Import(RestDocsConfiguration.class)
@ActiveProfiles("test") // 추가
public class EventControllerTests {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
// 테스트 코드 생략
}