Resource locking helps tests avoid conflicts when they use the same resource at the same time. It makes tests run safely without breaking each other.
0
0
Resource locking with @ResourceLock in JUnit
Introduction
When multiple tests access the same file and might change it.
When tests share a database and could interfere with each other's data.
When tests use a shared network connection or port.
When tests modify global settings or environment variables.
When running tests in parallel that use the same hardware device.
Syntax
JUnit
@ResourceLock(value = "resourceName", mode = ResourceAccessMode.READ) or @ResourceLock(value = "resourceName", mode = ResourceAccessMode.WRITE)
Use value to name the shared resource.
Use mode to specify if the test reads or writes the resource.
Examples
This locks the "database" resource for writing, so no other test can read or write it at the same time.
JUnit
@ResourceLock(value = "database", mode = ResourceAccessMode.WRITE)
void testUpdateDatabase() { ... }This locks the "configFile" resource for reading, allowing multiple reads but no writes during the test.
JUnit
@ResourceLock(value = "configFile", mode = ResourceAccessMode.READ)
void testReadConfig() { ... }Sample Program
This example shows two tests using the same resource "sharedFile". One test locks it for writing, the other for reading. JUnit will run them safely so they don't conflict.
JUnit
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.ResourceAccessMode; public class ResourceLockExample { @Test @ResourceLock(value = "sharedFile", mode = ResourceAccessMode.WRITE) void testWriteToFile() { System.out.println("Writing to shared file"); // simulate writing } @Test @ResourceLock(value = "sharedFile", mode = ResourceAccessMode.READ) void testReadFromFile() { System.out.println("Reading from shared file"); // simulate reading } }
OutputSuccess
Important Notes
Use WRITE mode when the test changes the resource.
Use READ mode when the test only reads the resource.
Tests with WRITE lock block other tests with READ or WRITE locks on the same resource.
Summary
@ResourceLock prevents tests from interfering when sharing resources.
Use resource names and access modes to control test access.
This helps tests run safely in parallel without errors.