This lesson introduces a substantial feature of JUnit Jupiter's parallel API, combatting one of the worst enemies of a concurrent environment: Flaky tests. When multiple tests are executed at the same time, it's possible for the assertions in each test to fail, simply because the shared state might have been mutated by the other test in an unexpected way. This leads to unpredictable execution and a bad experience for developers.
Tests that access common, shared resources, can be synchronized in JUnit Jupiter, using a feature called "resource locks". Annotating a test method with
@ResourceLock may lock the execution of other, similarly annotated methods, for as long as the test is being executed. Each annotation is given a string identifier, and if two methods have
@ResourceLocks with the same identifier, the TestEngine guarantees the complete execution of the first method, before the second one is started.
In our example, we can see the necessity of resource locks for unit tests of a shared resource, like
java.util.System.getProperties(). Furthermore, an advanced configuration of resource locks is explored: Each annotation can be put into either "read" or "write" mode, based on what the particular test is doing with the shared resource. This allows for limited parallelism of methods with the same resource lock, if both locks are set to "read" mode.
@ResourceLockto synchronize access to shared resources
- Provide string identifiers to the annotation; methods with the same identifier are locked together
- The first thread starting a method with a particular lock will prevent others from starting methods with the same lock
modeproperty on the annotation to notify the TestEngine of "read" or "write" access to the resource