Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel test case execution with JUnit 5

Tags:

java

junit

junit5

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)
like image 758
deamon Avatar asked May 29 '18 13:05

deamon


People also ask

Does JUnit 5 support parallel execution?

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.

Is parallel execution possible in JUnit?

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.

How do you perform parallel execution of test cases?

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.


1 Answers

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
like image 173
Mr.Turtle Avatar answered Sep 28 '22 08:09

Mr.Turtle