我正在尝试为我的Spring Boot应用程序引入一些单元测试,并且我正在努力设置测试环境的配置。我的应用程序已配置为连接两个不同的Postgres数据库,如下所示:
application.properties
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
在我的基本测试中,我试图测试一个注入了其中一个配置的repository的简单service。代码如下:
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
有关,但不知道为什么会出现这种情况。有什么想法吗?