How can I mock db connection in Spring Boot for testing purpose?

后端 未结 1 462
日久生厌
日久生厌 2020-12-30 04:37

Situation:

  1. I am using Spring Cloud with Spring Boot in a microservice, that microservice is loading a DB config information to config
相关标签:
1条回答
  • 2020-12-30 05:19

    There is an option to fake Spring bean with just plain Spring features. You need to use @Primary, @Profile and @ActiveProfiles annotations for it.

    I wrote a blog post on the topic.

    You can use in memory DB (e.g. H2) to replace real data source. Something like this:

    @Configuration
    public class TestingDataSourceConfig {
    
        @Bean
        @Primary
        public DataSource dataSource() {
            return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(H2)
                .setScriptEncoding("UTF-8")
                .ignoreFailedDrops(true)
                .addScript("schema.sql")
                .addScripts("user_data.sql", "country_data.sql")
                .build();
        }
    }
    
    0 讨论(0)
提交回复
热议问题