[Spring Boot] 스프링 테스트 DB 분리하기

Sarah·2026년 2월 15일

Spring Boot

목록 보기
16/17

테스트 코드를 돌리려고 했더니 기존 서버에 저장되어있는 데이터 때문에 충돌이 일어나 테스트 코드가 제대로 작동되지 않았다.

application.yml 생성

  • 생성 위치 test/resources/
  • test 하위에 resources 디렉터리가 없어서 새로 만들어주었다.
  • application.yml 파일을 그 안에 생성한다.
  • 아래 코드 작성
spring:
  jpa:
    hibernate:
      ddl-auto: create 
    show-sql: true
    properties:
      hibernate:
        format_sql: true
    defer-datasource-initialization: true
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

위 파일을 생성해봐도 테스트 코드를 실행하면 로그에 testdb가 뜨지 않고 서버 데이터를 사용했다.

@ActiveProfiles 어노테이션 추가

테스트 클래스 위에 @ActiveProfiles("test") 를 추가하니 드디어 테스트 데이터가 분리되었다.

profile
헤맨 만큼 내 땅

0개의 댓글