【问题标题】:Spring boot test: @Sql annotation Unable to locate sql files placed in src/test/resourcesspring boot测试:@Sql注解无法定位到src/test/resources中放置的sql文件
【发布时间】:2019-08-04 06:10:12
【问题描述】:

我不想加载整个 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(我更喜欢)

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

编辑:在配置类中添加static关键字

【问题讨论】:

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


    【解决方案1】:

    您的内部配置类将无法工作unless you add a static keyword before its definition。但是你应该知道@Sql注解

    路径资源语义

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

    所以尝试像这样在@Sql 中的值加上classpath: 前缀:

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

    祝你好运!

    【讨论】:

    • 默认情况下,src/main/resourcessrc/test/resources 是否都包含在类路径中?
    • 有时 vanilla java 不会根据您使用的运行器将 src/main/resources 添加到类路径中
    • +1 表示路径资源语义。 @Daud,您可能想查看 this 以了解有关资源的问题。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2013-09-04
      • 2020-11-14
      相关资源
      最近更新 更多