개발/Project

[springBoot] test용 h2 DB 설정하기

라니킴 2022. 1. 24. 08:08

springbootTest를 시행하면 연결되어있는 DB로 데이터가 이동된다.

rollback이 된다고 하더라도 데이터가 DB에 들어갔다 오는 것이기때문에 test환경에서만 사용할 수 있는 DB를 h2로 설정을 했다. 

 

* build.gradle 에 추가

testImplementation 'com.h2database:h2'

* FoodMapApplicationTests.java

@ActiveProfiles("test")
@SpringBootTest(properties = "classpath:application-test.yml")
@AutoConfigureMockMvc
class FoodMapApplicationTests {

    @Test
    void contextLoads() {
    }

}

* src/test/resources/application-test.yml

test 루트에 설정파일을 추가해준다. yml 파일 작성할 때는 띄어쓰기, 들여쓰기에 매우 유의해야한다!

spring:
  datasource:
    url: jdbc:h2:mem:test;MODE=MySQL
    username: sa
    password:
    driver-class-name: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create-drop

    properties:
      hibernate:
        format_sql: true
        dialect: org.hibernate.dialect.H2Dialect
logging:
  level:
    org.hibernate.SQL: debug

  cache:
    type: redis
  redis:
    host: localhost
    port: 6379

cache하는 부분에서 redis를 이용하고 있어서 같이 추가해줬다.

이제 springBootTest를 돌려도 기존 Mysql DB에는 영향이 가지 않는다.