我試圖啓動JUnit測試而沒有使用Hibernate。我的應用程序類:在Spring Boot中排除Hibernate無法正常工作
@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,但應以正確的方式進行配置(即指向內存數據庫)。這些觀點已被覆蓋到文檔的[集成測試](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html)部分。所以你試圖做的(兩者之間的混合)對我來說毫無意義,恕我直言。 –
實際上,仍然有很多組件不依賴於數據庫。事實上,依賴於它的部分非常小,但是所有測試都會啓動一個數據庫,當它們不依賴它時,它們不應該這樣做。但是我需要應用程序上下文,因爲它具有許多獨立配置,用於其中的多個組件。 –