Configure specific in memory database for testing purpose in Spring

前端 未结 7 810
粉色の甜心
粉色の甜心 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:06

    @Sanjay has one way to put it but I find it confusing. You could just as well have only a production profile that you enable when you're in production, something like:

    spring.jpa.hibernate.ddl-auto: update
    spring.datasource.url: jdbc:mysql://localhost:3306/dbname
    spring.datasource.username: username
    spring.datasource.password: password
    

    And don't specify anything else. If you add an embedded database in test scope, it will be available in your tests. If you run your tests with the default profile (no customization whatsoever), it won't find any database information (since these are stored in the production profile). In that case, it will try to find an embedded database and start it for you. If you need more customization for some reason, you can have a application-test.properties for those (you'll need to add ActiveProfiles("test") to your test(s).

提交回复
热议问题