How to "mock" the StructuredTaskScope for integration tests where we want to run every task sequentially instead of concurrently
Daniel Andres Pelaez Lopez
estigma88 at gmail.com
Tue Mar 25 20:35:16 UTC 2025
Hi all,
We were testing the JEP 499: Structured Concurrency (Third Preview) and
found a challenge.
Context:
We currently use Executor to create concurrent tasks, and when we create
integration tests using Spring Boot, we want to exercise the code in two
ways:
a. Executing the tasks sequentially, to validate that the use cases behave
as we expected. These tests are easy to setup.
b. Executing the tasks concurrently, to validate the logic is prepared to
handle concurrent behavior. These tests are not that easy to setup
The a. point will have many tests for all the possible branches, while b.
will have a few tests, focused only on the concurrent part.
For b. point, what we do today is to mock the Executor interface, as
follows:
Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
command.run(); // Directly runs the command in the calling
thread
}
}
That implementation guarantees that any tasks running over that executor
will run in the same thread, and therefore, sequentially.
Things get more complicated when you need to use ExecutorService. as the
interface is more cumbersome, so, creating a mock object from it is not
easy.
There is also the option to use Executors.newSingleThreadExecutor(), which
will have only one thread to run all the tasks, and therefore, it will need
to queue them in order. However, the downside of this approach is when you
want to run concurrent tasks but not join them to the current thread.
Challenge:
Testing JEP 499: Structured Concurrency (Third Preview) we couldn't find an
easy way to do this, perhaps we need to create a new StructuredTaskScope
implementation as we do with Executor interface? or should we pass a custom
ThreadFactory that only creates one thread?
Would like to know what you think about it. Thanks in advance
Daniel Andrés Pelaez López
e. estigma88 at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20250325/811c420f/attachment-0001.htm>
More information about the loom-dev
mailing list