spring 测试中配置hsqldb,与运行时数据库分开

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 production database [Postgre/MySQL] ?

方法1:

Spring profiles can be used for this. This would be a specific way:

Have environment specific properties files:

application.properties:

spring.profiles.active: dev

application-dev.properties

spring.jpa.database: MYSQL
spring.jpa.hibernate.ddl-auto: update

spring.datasource.url: jdbc:mysql://localhost:3306/dbname
spring.datasource.username: username
spring.datasource.password: password

application-test.properties

spring.jpa.database: HSQL

Have both MySQL and H2 drivers in pom.xml, like this:


    mysql
    mysql-connector-java
    runtime



    org.hsqldb
    hsqldb
    test

Last but not the least, annotate Test classes with @ActiveProfiles("test")

 

方法2:

Another approach is to add the annotation @AutoConfigureTestDatabase to you test class. My tests usually look like this:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
public class MyRepositoryTest {

    @Autowired
    MyRepository repository;

    @Test
    public void test() throws Exception {
        // Tests...
    }
}

方法3:

 

Simple solution if building with maven: just place an application.properties file under src/test/resources and edit as appropriate for testing.

The Spring (Boot) Profile mechanism is a pretty powerful tool that, in scope, goes way beyond "swapping settings between test time and run time". Although, clearly, as demonstrated, it can do that also :)

你可能感兴趣的:(spring)