【问题标题】:Spring boot integration test rollback does not workspring boot 集成测试回滚不起作用
【发布时间】:2017-12-26 11:13:45
【问题描述】:

在 Spring Boot 中,我尝试创建我的第一个事务测试,但事务不起作用。

@TestPropertySource(locations = "classpath:test.properties")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringJUnit4ClassRunner.class)
//@RunWith(SpringRunner.class)
@Transactional
@TestExecutionListeners(
    mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS,
    listeners = {TransactionalTestExecutionListener.class}
)
public class IntegrationTests
{
    @Autowired
    TemperatureLogRepository temperatureLogRepository;

    @Test
    @SqlGroup({
        @Sql(
            executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
            config = @SqlConfig(transactionMode = ISOLATED),
            scripts = "classpath:sqls/insertRecords2.sql"
        )
    })
    public void firstRepoTest() throws SQLException
    {
        assertThat(temperatureLogRepository.getFullList().size()).isEqualByComparingTo(0);
    }
}

我知道SqlGroup不是必须的,但是会添加更多的文件。

我现在拥有的:

  1. SQL 文件执行良好并插入数据库。
  2. getFullList() 方法可以读取它并返回正确的数据。
  3. 测试后我的数据库里还有数据,事务没有回滚。

我不确定它们是否在同一个事务中运行。是否可以在getFullList()方法运行之前将数据提交到db?

我需要什么:

  1. @Sql 将数据插入到事务中。
  2. getFullList() 从事务中读取数据。
  3. 测试返回的数据。
  4. 回滚交易。

【问题讨论】:

    标签: java spring spring-boot transactions integration-testing


    【解决方案1】:

    来自Spring Testing - Executing SQL scripts declaratively with @Sql

    脚本执行阶段

    默认情况下,SQL脚本会在相应的测试之前执行 方法。但是,如果需要执行一组特定的脚本 之后的测试方法 — 比如清理数据库状态 —  可以使用@Sql 中的 executionPhase 属性,如下所示 例子。请注意,ISOLATED 和 AFTER_TEST_METHOD 是静态的 分别从 Sql.TransactionMode 和 Sql.ExecutionPhase 导入。

    @Test 
    @Sql(
        scripts = "create-test-data.sql",
        config = @SqlConfig(transactionMode = ISOLATED) ) @Sql(
        scripts = "delete-test-data.sql",
        config = @SqlConfig(transactionMode = ISOLATED),
        executionPhase = AFTER_TEST_METHOD ) 
    public void userTest {
        // execute code that needs the test data to be committed
        // to the database outside of the test's transaction 
    }
    

    相关问题:How to execute @Sql before a @Before method

    更新

    @Sql 中删除@SqlConfig

    config = @SqlConfig(transactionMode = ISOLATED)
    

    或改为:

    config = @SqlConfig(transactionMode = TransactionMode.INFERRED)
    

    SQL 脚本在不回滚的单独事务中运行:

    org.springframework.test.context.jdbc.SqlConfig.TransactionMode.ISOLATED

    表示 SQL 脚本应始终以新的、 将立即提交的隔离事务。

    【讨论】:

    • 我正在使用befre阶段。查询运行良好。但我不想在测试后运行任何东西,我需要一个简单的回滚。我不想在数据库中提交任何内容。我的问题是回滚,看起来我有一个事务提交。
    • 更新了答案。
    • 我已经试过了。在这种情况下,测试后我在测试数据库中看不到任何内容,所以回滚很好,但我的仓库无法读取事务。还有什么想法吗? :)
    • 你有什么异常吗?我已经尝试过类似的配置并且它有效。
    • 也许您使用了超过 1 个数据源/数据库配置?
    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2011-11-28
    • 2017-04-15
    • 2019-08-10
    • 2022-08-21
    • 1970-01-01
    • 2017-01-05
    • 2011-03-08
    相关资源
    最近更新 更多