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


我试过将文件放在src/main/resources(不优选)和src/test/resources(我更喜欢)上

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

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

最佳答案

您的内部配置类将无法运行unless you add a static keyword before its definition。但是,您应该知道@Sql批注


  路径资源语义
  
  每个路径将被解释为一个Spring资源。一条简单的道路—为
  例如“ schema.sql”-将被视为
  是相对于定义测试类的包的。一条路径
  以斜杠开头的将被视为绝对类路径
  资源,例如:“ / org / example / schema.sql”。一条路径
  引用网址(例如,以classpath:,file:,http :、
  等)将使用指定的资源协议加载。


因此,尝试像这样在@Sql中用classpath:前缀值:

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


祝好运!

07-24 09:49
查看更多