how to use @DataJpaTest with multiple datasourse

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I tried to write integration test using annotation @DataJpaTest . I have two datasource: Primary and secondary (class config) in result i have an error:

expected single matching bean but found 2: primaryDataSource,secondary 

then i tried to add a annotation

@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED) 

and With AUTO_CONFIGURED only DataSources configured by properties will be replaced but instead embedded h2 i saw Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect

how using @DataJpaTest with multiple datasources ?

public class DataSourcesConfig {       @Bean     @Primary     @ConfigurationProperties(prefix="spring.datasource")     public DataSource primaryDataSource() {         return DataSourceBuilder.create().build();     }      @Bean(name = "secondary")     @ConfigurationProperties(prefix="datasource.secondary")     public DataSource secondaryDataSource() {         return DataSourceBuilder.create().build();     }  } 

回答1:

Found a possible solution here.

Basically you manually configure the H2 database appropriately instead of letting Spring do it automatically.

Create an application.properties file in “src/test/resources” with the following content

# Let Spring autodetect the different SQL Dialects of each datasource spring.jpa.database=default # Generate the DB schema in the In-Memory H2 databases based on the JPA Entities spring.jpa.generate-ddl=true  # H2 In-Memory Database "foo" (used in tests instead of a real PostgreSQL DB) spring.datasource.url=jdbc:h2:mem:foo;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa spring.datasource.password= spring.datasource.driver-class-name=org.h2.Driver  # H2 In-Memory Database "bar" (used in tests instead of a real PostgreSQL DB) bar.datasource.url=jdbc:h2:mem:bar;DB_CLOSE_ON_EXIT=FALSE bar.datasource.username=sa bar.datasource.password= bar.datasource.driver-class-name=org.h2.Driver 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!