如何在Spring DataJpaTest测试中阻止执行main/resources下的import.sql(不删文件)
这问题我熟!之前也碰到过类似的情况——想保留主代码里的import.sql,但测试时不想让它干扰测试数据对吧?给你几个靠谱的解决办法:
方法1:在测试类上直接覆盖配置(最便捷)
你可以直接在@DataJpaTest注解里添加properties参数,指定Hibernate的导入脚本为空,这样就不会触发main/resources下的import.sql执行了:
@RunWith(SpringRunner.class) @DataJpaTest(properties = "spring.jpa.hibernate.import_sql_files=") public class SomeIntegrationTest { @Autowired private SomeRepository someRepository; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } }
原理很简单:这个配置会覆盖默认的Hibernate导入脚本路径,设置为空后,Hibernate找不到要执行的导入文件,自然就跳过了那个HHH000476的脚本执行步骤。
方法2:用测试专用配置文件批量生效
如果有多个测试类都需要这个设置,推荐在src/test/resources下创建application-test.properties(或application.yml),添加以下配置:
# application-test.properties spring.jpa.hibernate.import_sql_files=
然后在测试类上激活这个配置文件:
@RunWith(SpringRunner.class) @DataJpaTest @ActiveProfiles("test") public class SomeIntegrationTest { // 你的测试代码不变 }
这样所有标记了@ActiveProfiles("test")的测试类都会自动应用这个配置,不用重复写配置参数。
方法3:针对旧版Spring Boot/Hibernate的兼容方案
如果你用的是Spring Boot 2.x之前的旧版本,可能需要用Hibernate原生的配置属性来覆盖:
@RunWith(SpringRunner.class) @DataJpaTest(properties = "hibernate.hbm2ddl.import_files=") public class SomeIntegrationTest { // 测试代码不变 }
或者在测试配置文件里写hibernate.hbm2ddl.import_files=,效果完全一致。
额外说明
为什么测试时会自动执行import.sql?因为@DataJpaTest默认会启动嵌入式数据库,并且Hibernate的ddl-auto属性默认是create-drop(Spring Boot自动配置的规则),这时候Hibernate会自动扫描classpath下的import.sql并执行。我们上面的配置就是通过覆盖导入脚本路径,让Hibernate找不到要执行的文件,从而跳过这一步。
内容的提问来源于stack exchange,提问作者Viktor M.

