Data Providers for BeforeMethod capabilities

Viewed 108

Is there a way to use Data Providers for BeforeMethod function? I would like to run parallel tests for number of different devices, so I would like to use parameters to setup capabilities. But I want to have a different way than using testng.xml.

1 Answers

You can get the data passed to the test by the data provider in your BeforeMethod by having Object[] parameter.

@BeforeMethod
public void beforeMethod(Object[] data) {
    //.......
}

Assume the following code:

@Test(dataProvider = "dataOne")
public void testMethodOne(String one, int two) {
}

@Test(dataProvider = "dataTwo")
public void testMethodTwo(int one) {
}

@DataProvider
public Object[][] dataOne() {
    return new Object[][]{ {"a", 1} };
}

@DataProvider
public Object[][] dataTwo() {
    return new Object[][]{ {1} };
}

In order to get the data passed by the data provider before it reaches the test methods, you define a before method as below. I have added Method m parameter as well. This would help to identify the running test case. Object[] data contains the data passed by the data provider. If you have added this argument, then testNG would automatically pass the data to the before method.

@BeforeMethod
public void beforeMethod(Method m, Object[] data) {
    if(m.getName().equals("testMethodOne")) {
        String x = (String) data[0];
        int y = (int) data[1];
    } else if(m.getName().equals("testMethodTwo")) {
        int x = (int) data[0];
    }
}
Related