因此,我正试图为我的Spring Boot应用程序引入一些单元测试,而我很难为测试环境设置配置。我的应用程序被配置为连接到两个不同的Postgres数据库,如下所示:
应用程序属性
spring.db1-datasource.jdbc-url= jdbc:postgresql://localhost:5432/db1
spring.db1-datasource.username= admin
spring.db1-datasource.password= admin
spring.db1-datasource.driverClassName= org.postgresql.Driver
spring.db2-datasource.jdbc-url= jdbc:postgresql://localhost:5432/db2
spring.db2-datasource.username= admin
spring.db2-datasource.password= admin
spring.db2-datasource.driverClassName= org.postgresql.Driver
FirstDbConfig.java
@Configuration
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
basePackages = "org.myapp.database.db1.repository",
entityManagerFactoryRef = "firstEntityManager",
transactionManagerRef = "firstTransactionManager")
public class FirstDbConfig {
@Autowired
private Environment env;
public FirstDbConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean firstEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(firstDataSource());
em.setPackagesToScan("org.myapp.database.db1");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
@ConfigurationProperties(prefix="spring.db1-datasource")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public PlatformTransactionManager firstTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(firstEntityManager().getObject());
return transactionManager;
}
}
SecondDbConfig.java
不包括它,因为它很相似。目标org.myapp.database.db2.repository
对于我的基本测试,我尝试测试一个简单的服务,该服务注入这些配置的存储库之一。看起来是这样的:
MyServiceTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyService.class)
@ContextConfiguration(
classes = {FirstDbConfig.class, SecondDbConfig.class },
loader= AnnotationConfigContextLoader.class
)
public class MyServiceTest {
@InjectMocks
private MyService myService;
@Mock
private FirstDbRepository dbRepository;
@Test
public void test() {
...
// call to myService.method()
}
}
测试失败:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set at ...
这显然与未设置hibernate.dialect
有关,但不知道为什么会出现这种情况。有什么想法吗?
是的,我们需要包含这个hibernate方言,试着在application.properties文件中包含这两行
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = update
需要将其包含在application.properties文件中spring.jpa.database=默认
您需要设置环境属性hibernate.dialect
,因为您正试图在代码中获取其值。