Java SpringBootTest失败-为什么在单个应用程序中测试schema.sql和data.sql会执行两次?

Java SpringBootTest失败-为什么在单个应用程序中测试schema.sql和data.sql会执行两次?,java,spring-boot,testing,spring-data-jpa,spring-boot-test,Java,Spring Boot,Testing,Spring Data Jpa,Spring Boot Test,您好,我正在编写一个SpringBoot应用程序,我正在编写单元测试和集成测试,但是我的集成测试失败了 原因1:它尝试通过执行schema.sql两次来创建表,因此表已存在。抛出异常,测试失败 原因2:即使我放置了创建如果不存在,当它第二次尝试执行脚本时,通过执行data.sql插入失败,并且发生唯一性约束冲突。我知道我可以在开始时删除表或删除记录以消除错误 但为什么要跑两次呢?不是三次还是一次 第一次测试 @SpringBootTest(webEnvironment = SpringBootT

您好,我正在编写一个SpringBoot应用程序,我正在编写单元测试和集成测试,但是我的集成测试失败了

原因1:它尝试通过执行
schema.sql两次来创建表,因此表已存在。抛出异常,测试失败

原因2:即使我放置了
创建如果不存在
,当它第二次尝试执行脚本时,通过执行
data.sql
插入失败,并且发生唯一性约束冲突。我知道我可以在开始时删除表或删除记录以消除错误

但为什么要跑两次呢?不是三次还是一次

第一次测试

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Atest {

}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Btest {

}
@SpringBootTest
public class Ctest {

}
第二次测试

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Atest {

}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Btest {

}
@SpringBootTest
public class Ctest {

}
第三次测试

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Atest {

}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Btest {

}
@SpringBootTest
public class Ctest {

}
AtestBtest都通过了
测试,他们试图从测试数据中访问记录,并且能够看到它。
但是Ctest
由于异常而失败

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "tbl_test" already exists; SQL statement:
因为在
test->resourcerece
文件夹
data.sql
schema.sql
中有两个文件。它尝试运行它们两次

我的问题:

  • 为什么脚本执行两次
  • 为什么不三次,每次测试一次
  • 我可以看到它们之间的唯一区别是
    @SpringBootTest
    @SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.NONE)
    ,但它们仍然处于一个执行周期或上下文中,因此不应该发生
  • 为什么当多个测试都有
    @SpringBootTest
    时它不会失败(就像三个测试都有这个注释一样)

  • 迪纳姆先生在评论中回答了这个问题:


    因为上下文不同。一个使用模拟环境运行,另一个不使用web环境。由于这种差异,它将加载一个新的应用程序上下文

    对此稍作扩展:Spring测试基础设施缓存用于测试的应用程序上下文。如果在多个测试中使用相同的配置设置
    ApplicationContext
    ,则将重用
    ApplicationContext

    由于
    ATest
    BTest
    使用相同的配置,因此它们使用
    ApplicationContext
    实例。由于
    schema.sql
    data.sql
    的执行发生在
    ApplicationContext
    的构建过程中,因此它们只执行一次


    CTest
    使用不同的配置,因此必须新创建
    ApplicationContext
    ,从而再次执行脚本。

    如果没有看到测试代码,就很难看出问题所在,因为上下文不同。一个使用模拟环境运行,另一个不使用web环境。由于这种差异,它将加载一个新的应用程序上下文。