Spring Boot集成测试无法找到SQL文件路径问题排查
问题描述
我在为REST API编写集成测试,需要在测试前初始化数据库,但系统报错无法找到SQL文件的路径。
测试代码
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @TestExecutionListeners(listeners = { SqlScriptsTestExecutionListener.class }) class OrderServiceApplicationTests { @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @Autowired private JobRepository jobRepository; //@Sql("INSERT INTO user_info(name) VALUES \"alex\" ") @Test @Sql("{/resources/schema.sql}") void shouldCreatePost() throws Exception { JobOrder job=jobRepository.save(createjob()); String request=objectMapper.writeValueAsString(job); mockMvc.perform(MockMvcRequestBuilders.post("/Job/Joborder") .contentType(MediaType.APPLICATION_JSON) .content(request)) .andExpect(status().is2xxSuccessful()); } JobOrder createjob(){ JobOrder job=new JobOrder(); job.setTitle("Hiring software engineer"); job.setDescription("responsible for developing and maintaining mobile app"); job.setRequirement("Need to know basic sql springboot,2 years exp"); job.setSalary(234); job.setOrder_id(1); return job; } }
schema.sql内容
INSERT INTO user_info (name) VALUES ('India');
报错信息
org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from class path resource [com/example/OrderService/{/resources/schema.sql}] at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:239) at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254) at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:54) at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.execute(ResourceDatabasePopulator.java:269) at org.springframewo
application.properties配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=*** spring.datasource.password=******* spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.defer-datasource-initialization=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.sql.init.mode=always
文件路径说明
schema.sql位于项目的src/main/resources目录下(对应类路径根目录)。
解决方法
- 修正@Sql注解路径格式:报错显示Spring在错误路径
com/example/OrderService/{/resources/schema.sql}查找文件,这是因为你用了错误的格式{/resources/schema.sql}。正确写法为:
也可以省略开头斜杠,直接写@Test @Sql("/schema.sql") void shouldCreatePost() throws Exception { // 原有代码 }@Sql("schema.sql")。 - 移除多余的监听器配置:Spring Boot测试默认已包含
SqlScriptsTestExecutionListener,无需手动添加@TestExecutionListeners注解,避免配置冲突。 - 确认资源文件编译路径:确保Maven/Gradle等构建工具会将
src/main/resources下的文件复制到类路径中,Maven默认会自动处理,Gradle需检查sourceSets配置。 - 可选:利用全局初始化配置:你的
application.properties已设置spring.sql.init.mode=always,Spring Boot会自动在启动时执行schema.sql,若无需仅在该测试中执行,可直接移除@Sql注解。
内容的提问来源于stack exchange,提问作者user20112858
相关产品推荐
相关产品推荐

