Reputation: 31
I have a Spring Boot application where I need to test everything. I have run into this problem.
When I launch my tests (for example from Gitlab pipeline), tests are running fast from the beginning. But the more tests are done, the slower it gets. Loading Spring application context for another test class gets slower and slower. I have also found out, that during the tests, database connections stays active and application lets go of them after all of the tests are finished, even though most of the classes have already finished a long time ago. Have anyone run into this problem before and found solution for it please?
My annotations used in tests:
// Service test class example
@ExtendWith(SpringExtension.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import({SomeService.class})
@Sql("classpath:testdata/some_test_data.sql")
public class SomeServiceTest {
// Controller test class example
@ComponentScan(basePackages = {"some.package.with.tests"})
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@SpringBootTest
@Transactional
@Sql("classpath:testdata/some_test_data.sql")
public class SomeControllerTest {
Upvotes: 0
Views: 2604
Reputation: 31
I was able to fix this problem with two steps:
Step 1: DirtiesContext annotation - This released DB connections after finishing tests from a specific class, so if I set maximum-pool-size: 5
it would now use only those 5 connections.
Usage:
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
Step 2: Increasing memory for tests - I also had to increase memory for Unit tests so I wouldn't get OutOfMemoryException
. MAVEN_OPTS
didn't work for me, so I had to use and configure plugin for this in pom.xml.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<argLine>-Xmx2048m</argLine>
</configuration>
</plugin>
After this, my test pipeline time was much faster. From about 20-30 minutes before, it now took 8 minutes.
Thank you very much @AndyWilkinson for your good advices
EDIT!!!! After this, my tests got coverage 0% reported on Sonar. After spending some time searching, I have found solution also for this:
Step 3: Define property sonar.surefire.argLine
<properties>
...
<sonar.surefire.argLine>-Xmx2048m</sonar.surefire.argLine>
</properties>
Step 4: Rewrite the plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<argLine>@{argLine} ${sonar.surefire.argLine}</argLine>
</configuration>
</plugin>
The problem here was, that jacoco plugin needs to have access to surefire's argLine, but after you add it manually, it is no longer possible. That's why I had to add @{argLine}
, which jacoco uses. ${sonar.surefire.argLine}
is just for better code appearance, so I could have -Xmx2048m
argument with other defined properties.
Upvotes: 1