Video in progress
How do you turn on running tests in parallel in JUnit 5, and what problems does it bring?
In junit-platform.properties you set junit.jupiter.execution.parallel.enabled=true and the modes. After that, tests with shared state (static fields, a shared database table, System.setProperty) start interfering with each other; you have to isolate them with @ResourceLock or @Isolated.
📖 Answer
# src/test/resources/junit-platform.properties
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=same_thread
junit.jupiter.execution.parallel.mode.classes.default=concurrent
junit.jupiter.execution.parallel.config.strategy=dynamic
With this setup, classes run in parallel while the methods inside one class run sequentially. It's the safest option to start with.
What surfaces once you turn it on:
- state cached in a
staticfield, or singleton fakes; - two tests doing
deleteAll()on the same table: one wipes the other's data; Locale.setDefault,TimeZone.setDefault, system properties: global for the whole JVM;- Mockito
mockStatic: it's thread-local, so it's less of a problem here, but it causes confusion if you don'tcloseit.
@ResourceLock("system-timezone")
class ReportTimezoneTest { ... }
@Isolated // while this class runs, nothing else runs
class GlobalConfigTest { ... }
One thing about Spring tests: the context cache is thread-safe, but the database in a single context is shared. So for Spring integration tests I often do parallelism not at the JUnit level but at the Maven/Gradle level (forkCount, maxParallelForks), with each fork having its own JVM and its own containers.
Sign up to mark studied questions and save your progress.