【发布时间】:2020-05-08 02:45:32
【问题描述】:
这是我第一次尝试使用 H2 内存数据库编写 Spring Boot 单元测试。我找到的指南使它看起来很简单,但我无法让它发挥作用。
H2 正在生成一长串语法错误,我相信尝试执行实体所需的所有 DDL。
我的单元测试类:
@RunWith(SpringRunner.class)
@DataJpaTest()
public class AppRepositoryTest
{
@Autowired
private TestEntityManager entityManager;
@Autowired
private OrganizationRepository organizationRepository;
@Test
public void test_findAppsForUserAndTeam()
{
// given
Organization organization = new Organization();
organization.setOrganizationCode("o");
organization.setOrganizationName("O");
entityManager.persist(organization);
entityManager.flush();
// when
Organization found = organizationRepository.getOrganizationWithParents("o")
.orElseThrow(() -> new RuntimeException("Org not found"));
// then
assertThat(found.getOrganizationName(), is("O"));
}
}
我要做的第一件事是创建架构,我将这一行添加到 resources/schema.sql 中:
CREATE SCHEMA IF NOT EXISTS EUAMDB;
运行测试失败,出现一长串语法错误,比如:
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table euamdb.public.access_requests if exists" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
...
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "DROP TABLE EUAMDB.PUBLIC.[*]ACCESS_REQUESTS IF EXISTS"; SQL statement:
drop table euamdb.public.access_requests if exists [42000-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:453) ~[h2-1.4.200.jar:1.4.200]
感谢任何帮助。
更新:
我知道我需要让 Spring 使用 euamdb 作为数据库名称(感谢@Evgenij)。目前它会生成一个随机数据库名称,正如我在日志中看到的那样:
Starting embedded database: url='jdbc:h2:mem:9929f516-5795-477c-8a8a-343b4b30ebf9;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
如果我在调试器创建数据源之前停止代码,并将随机数据库名称替换为“euamdb”,则测试运行。我只是不知道如何告诉 spring 使用什么作为 H2 数据库名称。
我已尝试更改@DataJpaTest 注释以将属性设置为:
@DataJpaTest(properties = {"spring.datasource.url=jdbc:h2:mem:euamdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false"})
还尝试添加此注释:
@TestPropertySource(properties = {
"spring.datasource.url=jdbc:h2:mem:euamdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false"})
最后修改了application.yml中的spring.datasource.url,但是这些都没有改变执行设置数据库名的方式。
【问题讨论】:
标签: spring unit-testing spring-data h2