【问题标题】:Prepare data for integration test with nested transactions with REQUIRES_NEW propagation使用 REQUIRES_NEW 传播为嵌套事务准备集成测试数据
【发布时间】:2020-10-21 23:22:35
【问题描述】:

您好,我们有层次结构,其中主要服务方法是@Transactional,另一个组件的调用方法也是@Transactional,但使用propagation = Propagation.REQUIRES_NEW。如果Bar 之一失败,它有理由确保其他实体将保存。问题是当我们准备 foo 实体来测试这个逻辑时。对于该嵌套事务,Prepared Foo 实体不可见。你能给我建议如何解决它吗?

我们的测试:

@Transactional
@ExtendWith(SpringExtension.class)
@SpringBootTest
class MainServiceImplTest {

    @Autowired
    private MainServiceImpl mainService;
    @Autowired
    private BarRepository barRepository;
    @Autowired
    private FooRepository fooRepository;

    @BeforeEach
    public void prepareFoos() {
        fooRepository.saveAndFlush(new FooEntity());
        fooRepository.saveAndFlush(new FooEntity());
    }

    @Test
    public void createBarsForAllFoosTest() {
        mainService.createBarsForFoos();
        Assertions.assertThat(barRepository.findAll()).hasSize(2); // failed - zero bars was saved
    }
}

以及我们的服务: 主要服务方式:

@Transactional
public void createBarsForFoos() {
    fooRepository.findAll().stream().forEach(fooEntity -> {
        try {
            nestedService.createBarForFoo(fooEntity.getId());
        } catch (Exception ex) {
            log.error("Saving of bar for foo with id {} failed.", fooEntity.getId());
        }
    });
}

以及带有新事务的嵌套服务:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void createBarForFoo(Long fooId) {
    Optional<FooEntity> fooOpt = fooRepository.findById(fooId);
    if (!fooOpt.isPresent()) {
        log.error("There is no foo with id {}", fooId);
        return;
    }
    barRepository.save(new BarEntity(fooOpt.get()));
}

【问题讨论】:

    标签: spring spring-boot spring-data-jpa spring-transactions


    【解决方案1】:

    你能试试吗:

    • 用@Transactional(包org.springframework.transaction.annotation)注释你的测试类
    • 将@BeforeEach 替换为@BeforeTransaction(包org.springframework.test.context.transaction)

    【讨论】:

    • 试过但没有帮助:/
    • 你能提供你的测试类是如何创建的以及你的 pom.xml/build.gradle 吗?因为您不是在模拟存储库,所以我猜您正在进行集成测试而不是单元测试?你有内存数据库依赖吗?
    • 我编辑了问题并添加了整个测试类。是的,它是与 postgresql db 的集成测试
    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2020-10-20
    • 2011-07-07
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多