Configure specific in memory database for testing purpose in Spring

前端 未结 7 812
粉色の甜心
粉色の甜心 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 14:15

    This solution enables common settings for develop and test. Is based on this solution: Override default Spring-Boot application.properties settings in Junit Test

    1. application.properties in src/main/resources/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
    
    1. test.properties (src/main/resources/application.properties) which overrides and adds properties in 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
    
    
    1. settings in pom.xml for H2 and Postgre databases
          
          
            com.h2database
            h2
          
    
        
          
             org.postgresql
             postgresql
          
    
    
    1. In test class:
        @RunWith(SpringRunner.class)
        @SpringBootTest
        @TestPropertySource(locations = "classpath:test.properties")
        public class ModelTest { 
    
        }
    

提交回复
热议问题