【发布时间】:2016-04-18 14:41:40
【问题描述】:
我正在尝试在没有休眠的情况下启动 JUnit 测试。我的应用程序类:
@SpringBootApplication(exclude = { HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class,
DataSourceAutoConfiguration.class, JpaBaseConfiguration.class, WebMvcAutoConfiguration.class })
@ComponentScan("my.base.package")
public class TestContext {
public static void main(String[] args) {
SpringApplication.run(TestContext.class, args);
}
}
如您所见,我排除了越来越多的东西,但总是出现同样的错误。我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestContext.class)
public class TestMail {
@Autowired
private Component c;
public void setC(Component c) {
this.c = c;
}
@Test
public void test() {
...
}
}
当我开始测试时,Hibernate 将被配置并失败:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active).
因此,仅启动应用程序或作为测试的上下文也会启动休眠配置。我做错了什么?
编辑: 只有:
@SpringBootApplication(exclude = { HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class})
在我尝试使用实际的休眠内容之前不会抛出任何异常。但是它正确地构建了数据库...
编辑2: 问题是具有 @EnableJpaRepositories 的自定义配置类。这似乎也是不可能的,因为使用 @Component 注释的具有自动装配存储库的 Bean 将失败,因为无法创建 bean。
【问题讨论】:
-
据我了解,您应该在没有 Spring 上下文的情况下进行单元测试并使用它进行集成测试。集成测试应该启用 Hibernate,但以正确的方式配置(即指向内存数据库)。文档的integration testing 部分很好地涵盖了这一点。所以你想做的事情(两者之间的混合)对我来说毫无意义,恕我直言。
-
其实还有很多不依赖于数据库的组件。事实上,依赖它的部分非常小,但所有测试都会启动一个数据库,当它们不依赖它时,它们不应该启动一个数据库。但我需要应用程序上下文,因为它对其中的多个组件有许多独立的配置。
标签: java spring hibernate spring-boot