0

I am trying to see if it is possible to have a setup run once for each parallel class instantiated.

If I have the following test class, because of the DataFactory (CSV has 2 rows of data, one for each test), two tests are started in parallel

Is it possible to get testSetup() to run once for each instance of the TestFu class. BeforeClass seems to run it once before both parallel test instances.

TestXML

<suite name="SomeTest" parallel="none" thread-count="20" verbose="2">
    <test name="Graph+APITests" parallel="instances" thread-count="5">
        <classes>
            <class name="TestFu" />
        </classes>
    </test>
</suite>

Test Class

public class TestFu {

    String var1;

    @Factory(dataProvider = "testStuff")
    public TestFu(String var1, String var2) {
        this.var1 = var1;
        this.var2 = var2;
    }

    @DataProvider(name = "testStuff")
    public static Object[][] stuff() {

        return methodThatLoadsVarsFromCSV;
    }

    @BeforeClass
    public void testSetup() {
        System.out.println("Doing setup");
    }

    @Test
    public void testOne() {
        System.out.println("Test 1 " + this.var1);
    }

    @Test
    public void testTwo() {
        System.out.println("Test 2 " + this.var2);
    }
}
dranobob
  • 796
  • 1
  • 5
  • 19

1 Answers1

1

Use static flag like this:

    static boolean initialized = false;

    @BeforeClass
    public void testSetup() {
        if (!initialized) {
            initialized = true;
            System.out.println("Doing setup");
        }
    }
Slavik
  • 1,488
  • 1
  • 15
  • 24
  • This is a simple but great idea. Would need to handle the two cases of more than one class entering the if block and to make sure all other classes wait for the setup to finish. We could add a randomized timer before the if block checking initialized to avoid any race condition where more than one class instance enters the if block but before setting initialized to true. We could add a second static boolean to check when the setup is done, then add an else to the if block that contains a loop for all of the classes waiting for the setup to be completed. – dranobob Jun 01 '19 at 21:36