spring-boot - 我使用@Sql进行Spring Test时发生FileNotFoundException

标签 spring-boot unit-testing gradle junit spring-test

我用Book倾斜Spring Boot。(从本书复制并粘贴到编辑器)
我无法理解并且无法使用代码。
您可以教我如何解决以及应该学习什么吗?

@Test
//@Sql("file:C:/Users/<username>/Desktop/springsample/src/test/resources/testdata.sql") //This is work!
@Sql("/testdata.sql") // This is not work.
public void countTest2(){
    assertEquals(dao.count(), 3);
}
请检查上面的代码,@Sql("/testdata.sql")不起作用。
Junit结果就是这样。

Caused by: java.io.FileNotFoundException: class path resource [testdata.sql] cannot be opened because it does not exist


所以我写了现在被注释掉的代码。有效。
我认为必须重写@Sql参数。但是我不知道该怎么做。
您能教我如何重写代码吗?
是否由于缺少Maven目录规则而导致此问题?
附录
目录树如下。
tree /F C:\Users\<username>\Desktop\springsample\src\test
C:\USERS\<username>\DESKTOP\SPRINGSAMPLE\SRC\TEST
├─java
│  └─com
│      └─example
│          └─springsample
│                  DemoApplicationTests.java
│                  UserDaoTest.java //Test code in this file.
│
└─resources
        testdata.sql
感谢您的阅读。
附加信息
我读了引用,然后尝试以下设置是可行的。
在这种情况下,需要将.sql文件放在与Test类文件相同的目录下。
我认为可以分配指定的位置。但是我不能。
@Sql("testdata.sql")
■目录树
C:\USERS\<username>\DESKTOP\SPRINGSAMPLE\SRC\TEST
├─java
│  └─com
│      └─example
│          └─springsample
│                  DemoApplicationTests.java
│                  UserDaoTest.java //Test code in this file.
│                  testdata.sql
└─resources
  └─com
      └─example
          └─springsample

最佳答案

默认情况下,@ Sql在@Test类的包中查找文件。
对于你的情况应该是如下

C:\USERS\<username>\DESKTOP\SPRINGSAMPLE\SRC\TEST
├─java
│  └─com
│      └─example
│          └─springsample
│                  DemoApplicationTests.java
│                  UserDaoTest.java //Test code in this file.
│
└─resources
│  └─com
│      └─example
│          └─springsample
│                  testdata.sql

关于spring-boot - 我使用@Sql进行Spring Test时发生FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64400469/

相关文章:

java - Spring简单示例: where create list of beans in JavaConfig?

Spring Cloud Stream 和@Publisher 注解兼容性

c# - 使用 Moq 安排单元测试

带有子模块的 Python 模拟补丁

java - 如何使用唯一 ID 记录错误并在 rest 响应中发送该 ID?

javascript - 诗浓 spy 的行为不符合预期

spring-boot - 列出 BOM 贡献给 gradle 5 的所有属性

Gradle 彩色输出(不再有 project.serviceOf() 或 services() api 方法)

gradle - 为什么命令行和DependsOn中的任务解析不同?

spring-boot 从@ConfigurationProperties 中删除位置属性