Initializing and clearing data for each test for parallel tests in TestNG

When porting some tests from JUnit to TestNG, I ran into a problem due to differences in the way these test environments handle instances of the test class.

JUnit creates a new instance of the Test class for each test method. So, the general template that I see is:

public class MyTest { private Stream inputData; @Before public void setUp() { // Set up some data in (non-static) instance fields // This data is isolated per test inputData = createInputDataStream(); } @Test public void testStuff() { // Use the data from the instance fields doStuff(inputData); } @After public void tearDown() { // Clean up the data from the instance fields closeInputDataStream(inputData); } } 

In contrast, TestNG uses one instance of the Test class for all test methods. So the above pattern does not work! Because data is stored in instance fields, values ​​are no longer isolated. This can lead to overwriting of intermediate data if parallel execution is enabled.

So how would I do this with TestNG? Is there a way to store data that is isolated for each set @BeforeMethod - @Test - @AfterMethod ?

I can do all 3 steps inside @Test itself, but for this I will need to add disappointing try...finally blocks to each test. I also tried using ITestContext , but it also seems to be common to the entire test run.

+5
source share
1 answer

Yes, with TestNG, you have more options than the local variables you made with JUnit, and DataProvider handles your stream processing for each instance of the test class:

 public class MyTest { private Stream inputData; @BeforeMethod public void setUp(Object[] args) { inputData = (Data)args[0]; inputData = normalizeDataBeforeTest(inputData); } @Test(dataProvider="testArgs") public void testStuff(Data inputDatax, Object a, Object b) { doSomethingWith(a); doSomethingWith(b); doStuff(this.inputData); } @AfterMethod public void tearDown() { // Clean up the data from the instance fields closeInputDataStream(inputData); } .... @DataProvider public static Object[][] testArgs() { // generate data here, 1 row per test thread Object[][] testData; for loop { // add row of data to testData // {{dataItem, obja, objb}, {dataItem, obja, objb}} etc. } return testData; } } 
+1
source

All Articles