【发布时间】:2017-07-16 06:32:34
【问题描述】:
我正在使用 Spring Boot 开发 Web 应用程序,现在我正在尝试为 DAO 层创建测试,我想使用不同的配置,它将读取自定义属性文件而不是标准配置文件。但是我遇到了麻烦,它总是读取默认应用程序。和hibernate.properties。
想要这样做是为了有不同的 hibernate.ddl-auto 属性进行测试。但是当我运行测试时,我看到 Spring 从资源文件夹中的 hibernate.properties 读取属性(我故意在该文件中打错字,以便在 Spring 读取该文件时出现异常)。但是为什么即使我使用@TestPropertySource,它也会读取该文件?
我看到有一些我不知道的东西,但是什么?
包src/test/java/com.guard/dao
@RunWith(SpringRunner.class)
@DataJpaTest
@Rollback
public class LifeguardDaoTest {
@Autowired
private LifeguardDao lgDao;
@Test
public void selectTest(){
for (Lifeguard lg :lgDao.getAll()) {
System.out.println(lg);
}
}
}`
测试配置类是设置上下文 包src/test/java/com.guard
@SpringBootApplication
@EntityScan(value = {"com.guard.dao","com.guard.model"})
@TestPropertySource(value = {"classpath:application-test.properties", "classpath:hibernate-test.properties"})
public class TestConfiguration {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(TestConfiguration.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
System.out.println("Spring boot test generated " + beanNames.length + " beans");
}
}
必需的 application-test.properties 和 hibernate-test.properties 位于 src/test/java 路径
这是项目结构(这里不知道怎么设计,不好意思)
|src
|--main
|----java
|------com.guard
|----------configuration
|-------------GuardApplication.class (@SpringBootApplication,requires default props)
|--test
|----java
|------application-test.properties
|-------hibernate-test.properties
|-----com.guard
|-------TestConfiguration.class
|-------dao
|---------LifeguardDaoTest.class
我的应用程序-test.properties `
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.HSQLDialect
spring.jpa.hibernate.show_sql=false
spring.jpa.hibernate.format_sql=true
spring.jpa.hibernate.hbm2ddl-auto=create
# even in case if it won`t use "spring.jpa" prefix
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
`
【问题讨论】:
标签: java spring hibernate spring-boot spring-test