05
Apr

dynamic data provider association for your TestNG scripts

Generally a script needs to be tested with multiple environments, where test data may differ. Following code snippet demonstrates how to associate different data providers to same testng script based on environment value:

Step 1: Create your normal TestNG scripts, which accepts dataprovider data:
—————————————————————————

import org.testng.annotations.Test;

public class TestNGScript {

@Test
public void myFunction(String s0){
System.out.println(s0);
}

}

Step 2: Create your Dataprovider class:
—————————————-

import org.testng.annotations.DataProvider;

public class myDPClass {

@DataProvider(name=”myDP”)
public Object[] myDP(){
return new Object[] {
“Sheetal”,
“Rastogi”
};
}

}

Step 3: Custom implement IAnnotationTransformer interface to associate data provider:
————————————————————————————–
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

public class MyIAnnotationTransformer implements IAnnotationTransformer {

public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
if (testMethod.getName() != null) {
annotation.setDataProviderClass(myDPClass.class);
annotation.setDataProvider(“myDP”);
}
}
}

Step 4: crate your testng.xml :
———————————








Output:
———-
[RemoteTestNG] detected TestNG version 6.14.3
Sheetal
Rastogi

===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================