Configure specific in memory database for testing purpose in Spring

前端 未结 7 795
粉色の甜心
粉色の甜心 2020-12-07 13:19

How do I configure my Spring Boot application so that when I run unit tests it will use in-memory database such as H2/HSQL but when I run Spring Boot application it will use

7条回答
  •  独厮守ぢ
    2020-12-07 13:55

    Simplest solution:

    1) in src/main/resources have application.properties (production config):

    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
    

    and application-test.properties with HSQL config like:

    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) Add HSQL dependency in pom.xml if you don't have it already.

    3) Annotate your test class with @ActiveProfiles("test").

    Worked like charm in my case.

提交回复
热议问题