Home > front end >  No transactional EntityManager found, is your test running in a transactional?
No transactional EntityManager found, is your test running in a transactional?

Time:06-24

I am writing tests for a repository, but BeforeAll annotation causes

java.lang.IllegalStateException: No transactional EntityManager found, is your test running in a transactional?

error. If I change it to BeforeEach the tests work, but that's not very efficient, since the same record is repeatedly written into the database. How can I fix this?

My test class:

@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ActiveProfiles("testing")
class RepositoryTest {

    @Autowired
    lateinit var entityManager: TestEntityManager

    val data = Data(...)
    
    @BeforeAll
    @Transactional
    fun setup() {
        entityManager.persist(data)
        entityManager.flush()
    }

    @Test
    func someTest() {
        assertEquals(1,1)
    }
}

CodePudding user response:

I think your problem is that @BeforeAll runs before the Dependency Injection. So your EntityManager is still null when you are trying to call entityManager.persist(data). Using a Constructor will result in the same problem.

CodePudding user response:

According to this question (and my own experience) @Transactional has no effect on methods annotated with @BeforeAll and similar. To get transactional behaviour, you need to add @Transactional to all the relevant @Test methods, or to the class as a whole (which then applies to every test method).

  • Related