java Spring Boot 1.4 @DataJpaTest - 创建名为“dataSource”的 bean 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41315386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot 1.4 @DataJpaTest - Error creating bean with name 'dataSource'
提问by Matt
I've created a new spring boot 1.4 application, want to try some testing using @DataJpaTest but keep getting the following error message
我创建了一个新的 spring boot 1.4 应用程序,想尝试使用 @DataJpaTest 进行一些测试,但不断收到以下错误消息
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot determine embedded database for tests. If you want an embedded database please put a supported one on the classpath.
引起:org.springframework.beans.factory.BeanCreationException: Error created bean with name 'dataSource': Invocation of init method failed; 嵌套异常是 java.lang.IllegalStateException:无法确定用于测试的嵌入式数据库。如果您想要一个嵌入式数据库,请在类路径上放置一个受支持的数据库。
src/main/resources/application.properties
src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost/my_db
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
MyRepositoryTest
我的存储库测试
@RunWith(SpringRunner.class)
@DataJpaTest
final public class MyRepositoryTest {
}
build.gradle
构建.gradle
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web',
'org.springframework.boot:spring-boot-starter-data-jpa',
'mysql:mysql-connector-java',
'org.projectlombok:lombok:1.16.10'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Any ideas what i am doing wrong?
任何想法我做错了什么?
回答by Stephane Nicoll
We don't provide an embedded database by default. By default DataJpaTestreplaces your DataSourcewith an embedded database but you don't have one.
默认情况下,我们不提供嵌入式数据库。默认情况下DataJpaTest用DataSource嵌入式数据库替换您的,但您没有。
So, if you want to test with MySQL, replace your test as follows:
因此,如果您想使用 MySQL 进行测试,请按如下方式替换您的测试:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = NONE)
final public class MyRepositoryTest {
}
If you want to use an in-memory database for those tests, you need to add one to the test classpath. Add this to your gradle file
如果您想对这些测试使用内存数据库,则需要在测试类路径中添加一个。将此添加到您的 gradle 文件中
testCompile('com.h2database:h2')

