【发布时间】:2019-10-03 13:01:07
【问题描述】:
我正在编写 junit 测试用例,发生了奇怪的事情 我有两个数据库
- 1) 广告系列(应用程序级别) 2) test(测试级别)
我的应用结构是
App
--> src/main/java
--> src/main/resource
application.yml
--> src/test/java
src/test/resource
application.yml
当我运行 Application 并加载 src/main/resource application.yml 文件并存储到内存中并指向 campaign 数据库时工作正常。 当我运行 Junit 测试用例 应用程序再次加载 src/main/resource application.yml 而不是加载 src/test/resource application.yml p>
当我强制运行测试用例时,应用程序指向test数据库 当我停止服务器并重新运行应用程序时,它再次指向 test 数据库而不是 campaign 数据库。
application.yml 用于 (src/main/resources) 或 (src/test/resources)
spring:
profiles.active: local
aop.proxy-target-class: true
---
spring:
profiles: local
campaignDB:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/campaign
username: root
password: Admin@123
juintDB:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: Admin@123
测试级别配置
@RunWith(SpringRunner.class)
public class TestDbConfig {
@Autowired
private Environment env;
@Bean
@Profile("local")
public DataSource testDbdatasource() {
org.apache.tomcat.jdbc.pool.DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource();
datasource.setDriverClassName(env.getRequiredProperty("juintDB.driverClassName"));
datasource.setUrl(env.getRequiredProperty("juintDB.url"));
datasource.setUsername(env.getRequiredProperty("juintDB.username"));
datasource.setPassword(env.getRequiredProperty("juintDB.password"));
return datasource;
}
}
应用级配置
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(datasource());
emf.setJpaVendorAdapter(hibernateJpa);
emf.setPackagesToScan("com.brighttalk.campaign.model");
Map<String, String> jpaSchema = new HashMap<String, String>();
jpaSchema.put("hibernate.default_schema",
env.getRequiredProperty("hibernate.default_schema"));
jpaSchema.put("hibernate.dialect",
env.getRequiredProperty("hibernate.dialect"));
jpaSchema.put("hibernate.format_sql",
env.getRequiredProperty("hibernate.format_sql"));
jpaSchema.put("hibernate.hbm2ddl.auto",
env.getRequiredProperty("hibernate.hbm2ddl.auto"));
jpaSchema.put("hibernate.show_sql",
env.getRequiredProperty("hibernate.show_sql"));
emf.setJpaPropertyMap(Collections.singletonMap(
"javax.persistence.validation.mode", "none"));
emf.setJpaPropertyMap(jpaSchema);
return emf;
}
我期望当我测试用例时它应该指向测试数据库。 当我运行应用程序时,它应该指向活动数据库。
【问题讨论】:
标签: java hibernate spring-boot junit yaml