use @Transactional with @BeforeEach test in java

Viewed 32

I have an integration test like this

@ExtendWith({SpringExtension.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@DirtiesContext
@Testcontainers
class TestIT {

@BeforeEach
public void beforeEach() {
    myRepository.save(myEntity);
}

@Test
void test() throws Exception {

    kafkaTemplate.send(event);
    TimeUnit.SECONDS.sleep(2);

    var result = myRepository.getById(id);
    assertThat(result).isEqualTo(expected);
    }
}

If I dont use @Transactional, I can see my entity in database physically, but I cant get result and have exception like org.hibernate.LazyInitializationException: could not initialize proxy - no Session. If I use @Transactional in beforeEach() or/and in test() I cant see my entity in db and my consumer also cant find it. I tried to use different propagination, but has the same result. How can I fix it? P.S. If I use @BeforeAll with Lifecycle.PER_CLASS and mark my test() method @Transactional it works ok. But I want to use @BeforeEach

0 Answers
Related