spring - 在 DataJPATest 下运行单元测试时出现问题
问题描述
这是我第一次尝试使用 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,但是这些都没有改变执行设置数据库名称的方式。
解决方案
我解决了这个问题,尽管这个解决方案并没有真正直接回答这个问题。
我确定不需要实体上 @Table 注释的 catalog = "euamdb" 部分。因此,当所有实体中的这些被删除时,测试就可以运行了。我也没有看到对应用程序有任何影响。
推荐阅读
- javascript - 角材料表动态行
- c - 使用指针在内存中迭代结构块
- reactjs - npm ERR 这可能不是 npm 的问题。上面可能有额外的日志输出
- java - 使用 Jackson 流式传输内部 JSONArray 记录,避免内存收集
- python - Python 在 Kali Linux Selenium 目录中找不到 Firefox Webdriver
- python-3.x - 如何使用 face_recognition 计算员工的活跃时间以进行考勤跟踪
- python - 使用 Flask (Python) 从 MySQL 数据库中获取“一些”数据
- python - Beautifulsoup 找不到标签
- redis - Drupal8设置redis键TTL
- android - 通过网络调用验证 android 中的 URL