春季启动测试:@Sql注释无法找到放置在src / test / resources中的sql文件

Dau*_*aud 1 java junit spring spring-boot spring-boot-test

我不想加载整个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
    }

}

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
Run Code Online (Sandbox Code Playgroud)

我尝试将文件放置在src/main/resources(不喜欢)和src/test/resources(我喜欢)这两个位置

注意:我正在通过Eclipse在Eclipse中运行单元测试Run as -> JUnit test

编辑:将static关键字添加到配置类

Abd*_*ssi 5

您的内部配置类将无法工作,除非您在其定义之前添加了static关键字。但是,您应该知道@Sql批注

路径资源语义

每个路径将被解释为一个Spring资源。普通路径(例如“ schema.sql”)将被视为相对于定义测试类的程序包的类路径资源。以斜杠开头的路径将被视为绝对类路径资源,例如:“ / org / example / schema.sql”。将使用指定的资源协议加载引用URL的路径(例如,以classpath:,file:,http:等开头的路径)。

因此,尝试像这样在内部@Sql添加前缀值classpath:

@Sql(scripts={"classpath:data.sql"})
Run Code Online (Sandbox Code Playgroud)

祝好运!