I want to create some test data in @BeforeTest method in parallel with threads to save data creation time. Test data to be used later in @Test methods. As a sample I have added Thread.sleep() for now. When I ran the test, once the threads are initiated and started on run() method, testNG executing @Test method even before all threads exiting run() method. I want the @Test Method to be executed once all the threads are out of run() method and exited @BeforeTest method. TestNG version: 7.0.0. Please help me solve this problem.
ThreadTest class
package mypackage;
public class ThreadTest implements Runnable{
public void run() {
// TODO Auto-generated method stub
//lines to create some test data
try {
System.out.println("In thread run method");
Thread.sleep(20000);
System.out.println("In thread out");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test Class:
package mytestpackage;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import mypackage.*;
public class TestClass {
@BeforeTest
public void beforeTest() {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
for(int i=0;i<10;i++) {
ThreadTest threadObj = new ThreadTest();
executor.execute(threadObj);
}
executor.shutdown();
System.out.println("Active thread count "+executor.getActiveCount());
}
@Test
public void testMethod() {
System.out.println("In Test Method");
}
}
Sample Output:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running mytestpackage.TestClass
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator@4f4a7090
In thread run method
In thread run method
In thread run method
In thread run method
In thread run method
Active thread count 5
In Test Method
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.648 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.083 s
[INFO] Finished at: 2022-08-04T20:49:11+05:30
[INFO] ------------------------------------------------------------------------