I have a bunch of @DataJpaTests
as well a lot of @SpringBootTests
and @WebMvcTests
.
I also have @EnableJpaAuditing
enabled.
When I run @DataJpaTests
independently it's all fine, these tests run and pass successfully. But if I run all the tests at once, some @DataJpaTest
throw occasionally the following:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaAuditingHandler': Cannot resolve reference to bean 'jpaMappingContext' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalStateException:
org.springframework.web.context.support.GenericWebApplicationContext@15405bd6 has been closed already
The problem is that I don't see a pattern here. Sometimes I get this exception, sometimes not. Some @DataJpaTest
throw this exception, some not... So I'm not sure how to prevent it.
This answer helped me to resolve my problem.
I created an abstract class:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public abstract class BaseDataJpaTest {}
And inherit all my @DataJpaTest
from this class.
This way I get a fresh context before each test.