【问题标题】:How to test a RollBack in a DataJPATest如何在 DataJPATest 中测试回滚
【发布时间】:2022-12-29 19:51:49
【问题描述】:

有一个服务类,其方法注释为@Transactional。它确实插入了一些数据(entityA),而不是添加下一个数据(entityB)时我希望它回滚第一个插入的数据。

只需添加 @Transactional 就可以解决手动测试问题。 这是服务的伪实现:

public class EntityAService {
    private EntityARepository repository;
    private EntityBService serviceEntityB;

    @Transactional
    public void persistComplexData(ComplexData data) {
        EntityAData entity = data.getAData();
        repository.create(entity); 

        EntityBData entityB = data.getBData();
        serviceEntityB.insert(entityB); // Will throw exception and rollback entire method.
    }
}

为了测试我正在使用@DataJPATest,在它的文档中说

默认情况下,用 @DataJpaTest 注释的测试是事务性的,并在每个测试结束时回滚。

所以我的测试看起来像这样:

@DataJpaTest
public class EntityAIntegrationTest {
    EntityAService service;
    EntityARepository repository;

    @Test
    public void createEntityBShouldNotCreateEntityA() {
        // Before alredy has one from test setup, next insert should fail cause conflics.
        assertThat(repository.findAll()).hasSize(1);

        ComplexData data = ComplexData.builder()
            ...
            .build();

        assertThrows(InternalValidationException.class, () -> service.persistComplexData(data));

        assertThat(repository.findAll()).hasSize(1); // <== Should be ok, but returning 2

    }
}

试图添加 TestTransaction.start(),但我收到错误消息,提示应该在初始化新事务之前完成现有事务。

PS:刚跑的时候createEntityBShouldNotCreateEntityA测试,它按预期工作。与其他人一起跑步时得到 2 个而不是 1 个。与多个人一起跑步时即使改变也会得到这个结果createEntityBShouldNotCreateEntityA成为第一个测试运行。

【问题讨论】:

    标签: java spring-boot testing integration-testing


    【解决方案1】:

    据我从你的测试中可以看出,抛出的异常是一个InternalValidationException,这是一个已检查的异常(我不能确定,因为你没有提供包名称)。

    当您使用 @Transactional 注释时,它不会回滚已检查的异常。

    尝试在你的persistComplexData(..) 方法上做这样的事情。

    @Transactional( rollbackFor = InternalValidationException .class)

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2018-01-25
      • 1970-01-01
      • 2019-09-23
      • 2018-01-18
      • 2023-02-08
      • 2021-02-03
      • 2019-12-20
      相关资源
      最近更新 更多