ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • REQUIRES_NEW 전파를 사용하여 중첩 된 트랜잭션으로 통합 테스트를위한 데이터 준비
    카테고리 없음 2020. 8. 17. 01:50

    질문

    안녕하세요, 우리는 @Transactional인 메인 서비스 메소드, @Transactional인 다른 컴포넌트의 메소드를 호출하지만 propagation = Propagation.REQUIRES_NEW <가있는 계층 구조가 있습니다. / code>. Bar중 하나가 실패하면 다른 엔티티가 저장되도록 할 이유가 있습니다. 문제는이 논리를 테스트하기 위해 foo 엔티티를 준비 할 때입니다. 중첩 된 트랜잭션에 대해 준비된 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()));
    }

    답변1

    시도해 볼 수 있습니까?

    • @Transactional(패키지 org.springframework.transaction.annotation )으로 테스트 class에 주석을 추가합니다.
    • @BeforeEach @BeforeTransaction(패키지 org.springframework.test.context.transaction )으로 바꿉니다.


     

     

     

     

    출처 : https://stackoverflow.com/questions/62678068/prepare-data-for-integration-test-with-nested-transactions-with-requires-new-pro

    댓글

Designed by Tistory.