gpt4 book ai didi

java - Spring 启动测试 : @Sql annotation Unable to locate sql files placed in src/test/resources

转载 作者:行者123 更新时间:2023-11-29 07:24:54 27 4
gpt4 key购买 nike

我不想加载整个 Spring Boot 配置来对我的 DAO 层进行单元测试,因此创建了一个嵌套配置类来抑制默认配置。但是当我尝试指定 SQL 脚本让它在测试前运行时,它无法找到它们。

代码如下:

package com.test.customer.controller;
..
@RunWith(SpringRunner.class)
@JdbcTest
@Sql({"data.sql"})
public class InterviewInformationControllerTest {

@Configuration
static class TestConfiguration{

}

@Test
public void testCustomer() {
// code
}

}

我得到错误:

Cannot read SQL script from class path resource [com/test/customer/controller/data.sql]; 
nested exception is java.io.FileNotFoundException:
class path resource [com/test/customer/controller/data.sql]
cannot be opened because it does not exist

我已经尝试将文件放在 src/main/resources(不是首选)和 src/test/resources(我更喜欢)

注意:我通过执行 Run as -> JUnit test 从 Eclipse 内部运行单元测试。

修改:在配置类中添加了static关键字

最佳答案

你的内部配置类将不起作用unless you add a static keyword before its definition .但是你应该知道对于 @Sql 注释

Path Resource Semantics

Each path will be interpreted as a Spring Resource. A plain path — for example, "schema.sql" — will be treated as a classpath resource that is relative to the package in which the test class is defined. A path starting with a slash will be treated as an absolute classpath resource, for example: "/org/example/schema.sql". A path which references a URL (e.g., a path prefixed with classpath:, file:, http:, etc.) will be loaded using the specified resource protocol.

所以尝试在 @Sql 中使用 classpath: 作为前缀,如下所示:

@Sql(scripts={"classpath:data.sql"})

祝你好运!

关于java - Spring 启动测试 : @Sql annotation Unable to locate sql files placed in src/test/resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com