Spring Boot Version: 2.5.4
I am having the problem to use a TestEntityManager
in a SpringBootTest
. Basically, I followed the instruction from here where it says:
If you want to use
TestEntityManager
outside of@DataJpaTest
instances, you can also use the@AutoConfigureTestEntityManager
annotation.
This seems to be the same issue as #27146 which had been closed due to inactivity though.
I attached a zip with a minimal example. The error message can be reproduced by running the DemoApplicationTests. spring-test-problem.zip
Error message: java.lang.IllegalStateException: No transactional EntityManager found
Note: I am using JUnit 4 and h2 database. Is this a problem?
Comment From: wilkinsona
Thanks for providing a sample. The problem is occurring because your tests are not @Transactional
. Annotating your test class or method with org.springframework.transaction.annotation.Transactional
will fix it. We can use this issue to clarify the documentation.
Comment From: wilkinsona
We could maybe also improve the message in the assertion in TestEntityManager.getEntityManager()
. It currently says "No transactional EntityManager found". Perhaps we should say something like "No transactional EntityManager found. Are your tests annotated with @Transactional
?" instead.
Comment From: rd-malte-mauelshagen
Yes that would be great!
Also, while you are at it, you could improve the documentation here because in the code snippet the method is NOT annotated with @Transactional
. I guess it is because it's a JPA Test and not a SpringBootTest? Either way, some more information there and in the error message would be helpful!
Comment From: wilkinsona
@DataJpaTest
is itself annotated with @Transactional
so any class annotated with @DataJpaTest
is implicitly @Transactional
as well. It's only when you're using @SpringBootTest
(where tests are not transactional by default) and @AutoConfigureTestEntityManager
that you need to explicitly use @Transactional
as well.
Comment From: wilkinsona
Closing in favor of #28086.