With a test such as this:
@DataJpaTest
class PersonRepositoryTest {
@Autowired
private PersonRepository personRepository;
@Autowired
private TestEntityManager em;
@BeforeEach
void setup() {
em.persistAndFlush(new Person());
}
@Test
void shouldFindAllPersons() {
Iterable<Person> result = personRepository.findAll();
assertThat(result).hasSizeGreaterThanOrEqualTo(1);
}
@Nested
@TestPropertySource(properties = "spring.config.additional-location=optional:file:data.yaml")
class FindAll {
@Test
void shouldFindAllPersons() {
Iterable<Person> result = personRepository.findAll();
assertThat(result).hasSizeGreaterThanOrEqualTo(1);
}
}
}
The test in the @Nested
class fails with jakarta.persistence.TransactionRequiredException: no transaction is in progress
The test in the outer class works fine.
Removing the @TestPropertySource
results in all tests passing, however in the test I'm actually working on, I need that to work around another bug. I assume that there are other scenarios which might cause this issue as well. I've spent some time debugging this, and it appears that 2 LocalContainerEntityManagerFactoryBean
s are created - the transaction is started with one of them, but the code in the @BeforeEach
is executed using the other. This results in the TransactionSynchronisationManager
not finding the EntityManagerHolder in doGetResource()
.
The issue is present in 3.2.3, 3.2.12 and 3.4.3, and presumably everything in-between.