【问题标题】:Reading.sql file from custom location other than resouces folder using @sql spring boot test使用@sql spring boot test从资源文件夹以外的自定义位置读取.sql文件
【发布时间】:2020-11-14 00:21:13
【问题描述】:

您好,我已经使用 spring data jpa test 编写了测试用例。当我将 data.sqlschema.sql 文件放入 test/resources 文件夹时,测试用例运行良好,即使由于 Spring Boot 测试的默认行为而没有使用 @Sql 注释。

但我的要求是我有一个与主文件夹和测试文件夹平行的文件夹,即我的 data-h2.sql 和 schema-h2.sql 文件所在的 integrationTest。问题是我无法使用@Sql Annotation 读取这些 sql 文件。如何给出路径以便我可以从任何给定的自定义位置读取 sql 文件

下面是文件夹结构和代码供参考

代码

@DataJpaTest
@Sql(scripts={"/integrationTest/schema-h2.sql", "/integrationTest/data-h2.sql"})
public class AbcRepositoryTest extends AbstractTestNGSpringContextTests {

}

错误

08:44:45.329 [测试工作者] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL 错误:90079,SQLState:90079 08:44:45.329 [测试工作者] 错误 o.h.e.jdbc.spi.SqlExceptionHelper - 找不到模式“TEST”; SQL语句:

【问题讨论】:

  • 自定义位置是什么意思?你的schema-h2.sql的绝对路径是什么
  • @KavithakaranKanapathippillai 绝对路径是 /data/sfsf/workspace/timeevent/tenant-creation/8669/online/time/src/integrationTest/resources/schema-h2.sql 其中 online 是根项目下什么时候是子项目
  • 试试file:src/integrationTest/resources/schema-h2.sql。如果它不起作用file:/data/sfsf/workspace/timeevent/tenant-creation/8669/online/time/src/integrationTest/resources/schema-h2.sql

标签: java spring-boot junit spring-boot-test java-resources


【解决方案1】:

在挣扎 3 到 4 小时后找到了我发布的问题的解决方案 我们需要使用 SqlScriptsTestExecutionListener 以便从您选择的自定义位置读取 @Sql 脚本并放置 DirtiesContext 以便为每个测试用例运行 @Sql 脚本。

@DataJpaTest
@TestExecutionListeners(listeners = { SqlScriptsTestExecutionListener.class })
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@Sql(scripts = {"file:src/integrationTest/resources/schema-h2.sql","file:src/integrationTest/resources/data-h2.sql"})
public class AbcRepositoryTest extends AbstractTestNGSpringContextTests {
}

UsefulLink 帮助解决问题

https://github.com/spring-projects/spring-framework/issues/18929

How can Spring's test annotation @Sql behave like @BeforeClass?

Using annotation @Sql, is it possible to execute scripts in Class level before Method level?

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 2019-10-16
    • 2019-04-15
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    相关资源
    最近更新 更多