Is it possible to execute a test case parallel with JUnit 5?
I'm looking for something like threadPoolSize
and invocationCount
from TestNG:
@Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000)
Yes, in this post, I will explain to you how to use JUnit 5 Parallel Test Execution feature. This is an experimental feature of JUnit 5 and it will come from after JUnit 5.3. To enable parallel execution, simply set the junit. jupiter.
By enabling parallel execution, the JUnit engine starts using the ForkJoin thread pool. Next, we need to add a configuration to utilize this thread pool. We need to choose a parallelization strategy. JUnit provides two implementations (dynamic and fixed) and a custom option to create our implementation.
To trigger parallel test execution in TestNG, i.e., run tests on separate threads, we need to set the parallel attribute. This attribute accepts four values: methods – runs all methods with @Test annotation in parallel mode. tests – runs all test cases present inside <test> tag in the XML in parallel mode.
You can write parallel tests with JUnit 5.3. https://junit.org/junit5/docs/current/user-guide/#writing-tests-parallel-execution
@Execution(ExecutionMode.CONCURRENT)
class MyTest {
@Test
void test1() throws InterruptedException {
Thread.sleep(1000);
System.out.println("Test1 " + Thread.currentThread().getName());
}
@Test
void test2() throws InterruptedException {
Thread.sleep(1000);
System.out.println("Test 2! " + Thread.currentThread().getName());
}
}
// should run simultaneously
Remember to add the junit.jupiter.execution.parallel.enabled=true
to your JUnit configuration
https://junit.org/junit5/docs/current/user-guide/#running-tests-config-params
Add this to your JUnit configuration if you need a fixed thread pool
:
junit.jupiter.execution.parallel.config.strategy=fixed
junit.jupiter.execution.parallel.config.fixed.parallelism=4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With