2017-02-21 71 views
5

我有一个弹簧启动应用程序,它有几个@Entity类和@RepositoryRestResource repositort接口。现在我想写一些测试,在那里我可以检查是否可以使用这些存储库向数据库中添加新记录,但我不想使用配置的MySQL数据库,但是我想使用一些嵌入式数据库像H2。目前,我有一个application.properties文件,它看起来像这样:使用嵌入式数据库进行弹簧启动测试

spring.jpa.hibernate.ddl-auto=create 
spring.datasource.url=jdbc:mysql://localhost:3306/mydb 
spring.datasource.username=root 
spring.datasource.password=qwerty123 

问题:如何配置我的应用程序使用其他分贝测试?我的项目中没有xml,所有内容都基于注释。我尝试使用@Bean来定义@Configuration类以创建DataSource,然后在测试类中使用它与@ContextConfiguration注释,但它说它无法加载上下文。

回答

13

如果您正在使用Maven项目,则可以将application.properties文件添加到您的src/test/resources中,例如使用以下内容。

# Create DDL 
spring.jpa.hibernate.ddl-auto=create 

# H2 in local file system allowing other simultaneous connections 
spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE 

此外,您还需要包括H2的依赖(pom.xml):

<dependency> 
    <groupId>com.h2database</groupId> 
    <artifactId>h2</artifactId> 
    <version>1.4.193</version> 
</dependency> 
+0

它仍然使用MySQL数据库,而不是如果我这样做的。我应该提供关于测试课程的更多信息吗?一些注释明确定义这些属性而不是来自'main'文件夹的那些注释? –

+0

好吧,我添加了@PropertySource(“路径/到/属性”)'注释测试类,现在它的工作原理,谢谢 –

相关问题