Spring 启动测试:@Sql 注释无法定位 sql 文件放置在 src/test/resources

Spring boot test: @Sql annotation Unable to locate sql files placed in src/test/resources

我不想加载整个 Spring 引导配置来对我的 DAO 层进行单元测试,因此创建了一个嵌套配置 class 到 抑制默认配置。但是当我在测试前尝试为它指定 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
    }

}

I get the error: 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关键字class

您的内部配置 class 将不起作用 。但是你应该知道对于 @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"})

祝你好运!

检查模块的 out 目录。在资源中创建目录时,如果直接使用 com.gakshintala.bookmybook 等命名空间命名,它将完全将该名称作为目录名称,因此 out 也包含此目录下 resources 与姓名 com.gakshintala.bookmybook。 PFB 对与错。上对下错

Spring 总是寻找嵌套目录 resources->com->gakshintala->bookmybook。 所以创建那个目录结构。