TestNg : How to run a method only once for multiple objects in DataProvider

442 Views Asked by At

I have a DataProvider with 2 objects, so TestNg considers it 2 test cases. Hence if i use @BeforMethod that will also run twice.

@DataProvider
public static Object[][] dp() {

    return new Object[][]{
            {new Object1()},
            {new Object2()}
    };
}

I want to run methodA() only once no matter how many iterations of objects are being returned from data provider and methodB() needs to run every time.


@Test(dataProviderClass = DataProvider.class, dataProvider = "dp")
   methodA();
   methodB();
}

I searched and found I can maybe use a boolean which will let me know if method was executed or not and after executing it once i can set boolean to true, but there are multiple test cases in my class so not sure how that will handle all the test cases. Any elegant solution for this available?

I was thinking if somehow I could get count of objects from dataprovider that could also help. Any help would be appreciated.

tried with

boolean isExecuted = false;

if(!isExecuted) {
  methodA();
  isExecuted=true;
}

but this only works for 1 test case, i have multiple test cases in my class.

1

There are 1 best solutions below

0
Alexey R. On

You can use two data providers. One would take first value from another. So that the code would look like:

public class NewTest {

    @DataProvider(name = "commonCase")
    public Object[][] dp(){
        return new String[][]{
                {"My str1"},
                {"My str2"},
                {"My str3"}
        };
    };

    @DataProvider(name = "specialCase")
    public Object[][] dpSpecial(){
        return new Object[][]{
                dp()[0]
        };
    }

    @Test(dataProvider = "specialCase")
    public void testA(String val){
        System.out.println(val);
    }

    @Test(dataProvider = "commonCase")
    public void testB(String val){
        System.out.println(val);
    }

}