The code snippet you have provided does not actually supply any data to your test and actually does not use context or method information.
The idea is that TestNG as a framework knows everything about your test execution. For example it maintains the object that holds the context of your execution. What the context
is is defined within ITestContext
interface. There is a number of useful methods that let you watch the overall execution state and exchange the data within the execution (for example put some object to a "global" storage in one test and access it in another test within the same execution).
So, when you run your tests, TestNg
looks up all the methods which are annotated as, say, @DataProvider
(in your case). Then it checks what types the method parameters have (considering the order). If it encounters the type ITestContext
it injects that object (which holds execution context) and thus, you can just use it in your code and be sure you will get the context when your code will go runtime.
Below is my example demonstrating some aspects of how you can use this:
public class DataProviderExample {
@DataProvider(name = "example")
Iterator<Object[]> sampleDP(ITestContext context){
Iterator<Object[]> data = new Iterator<Object[]>(){
Object[] innerData = new String[]{
"MyData 1",
"MyData 2",
"MyData 3"
};
final int SIZE = innerData.length;
int currentItem = 0;
@Override
public boolean hasNext() {
return currentItem < SIZE;
}
@Override
public Object[] next() {
return new Object[]{
innerData[currentItem++],
context.getStartDate()
};
}
};
return data;
}
@Test(dataProvider = "example")
public void sampleTest(String arg1, Date arg2){
System.out.println(arg1 + " : " + arg2.toString());
}
}
Probably here is quite a lot of lines for just the example, and I apologize for that since the most of the lines address Iterator object description. The main idea shown in the example is that we can, say, take some information from the execution context and add it to the test data that is supplied by data provider.
The output would look like this:
MyData 1 : Thu Dec 20 11:11:28 MSK 2018
MyData 2 : Thu Dec 20 11:11:28 MSK 2018
MyData 3 : Thu Dec 20 11:11:28 MSK 2018
===============================================
Default Suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================
P.S. - The same conception you can apply to Method
object.
P.P.S. - Despite my example does not add a lot of value in real life, since you can just get the startDate
from the context straight from the test (using the same approach), it demonstrates how you can access the context from your code. I think the most useful thing one could do with the context in dataProvider
method is to use it in order to take decisions on what data to provide. For example you could check the execution date and prepare your data in different way on, say, a weekend.