Video in progress

Senior 🧪 Testing

The test stage in CI takes 25 minutes. How do you analyze it and cut it down?

First I measure: how many Spring contexts are started, which are the 20 slowest tests, how many times the containers start. Usually most of the time goes to the number of contexts and Docker containers started over and over; after that comes parallelism and sharding.

📖 Answer

Before blindly setting forkCount, I collect data:

  • per-class times from the Surefire/Gradle report: the slowest 20 usually take half the total time;
  • logging.level.org.springframework.test.context.cache=DEBUG: how many contexts were created. 3-5 is normal, 40 is a problem;
  • Testcontainers logs: how many times Postgres started.

Then in order:

  1. Merge contexts. A shared base class, the same set of @MockitoBeans, remove the @DirtiesContexts. Often this one step halves the time.
  2. Make the containers singletons. One JVM, one Postgres, one Kafka.
  3. Tests at the wrong layer. If @SpringBootTest + a real database was used just to check validation, I move it down to @WebMvcTest or a pure unit test.
  4. Remove the sleeps. Grep for Thread.sleep(5000) lines: each one is 5 seconds.
  5. Parallelism. JUnit parallel for unit tests; for integration tests, Gradle maxParallelForks or Maven forkCount, each fork with its own containers.
  6. Sharding at the CI level. Split the tests across 4 jobs, balanced by timings from previous runs.

One thing I'm careful about: switching off integration tests and moving them to "nightly" to speed things up. That shortens the time, but bugs get found after they've reached main, and fixing gets more expensive.

I turn the result into a metric: the test stage's p50/p90 time on a dashboard. Otherwise it creeps back to 25 minutes in 6 months.