How can we name a test case dynamically when using a data provider
How can we call the test case dynamically when using the data provider, for example:
If I have a login script and I want to use a data provider for different usernames and passwords, where each user represents a country, how can I get the test result or pass but with a different test case name, for example I should like the following:
loginTestUSusername pass
loginTestINusername pass
loginTestJPuserName pass
Note that the method name is loginTest and the appended USusername,INusername,JPusername
data is test data from the data provider
source to share
Follow these steps:
Step 1:
Create a custom annotation in a separate file (ex: SetTestName.java )
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTestName {
int idx() default 0;
}
Step # 2:
Create a base class that implements the TestNG ITest interface ( TestNameSetter.java ).
public class TestNameSetter implements ITest{
private String newTestName = "";
private void setTestName(String newTestName){
this.newTestName = newTestName;
}
public String getTestName() {
return newTestName;
}
@BeforeMethod(alwaysRun=true)
public void getTheNameFromParemeters(Method method, Object [] parameters){
SetTestName setTestName = method.getAnnotation(SetTestName.class);
String testCaseName = (String) parameters[setTestName.idx()];
setTestName(testCaseName);
}
}
Step # 3:
Use your DataProvider as in the code snippet:
@DataProvider(name="userData")
public Object[][] sampleDataProvider()
{
Object[][] data = {
{"loginTestUS_Username","loginTestUSPass"},
{"loginTestIN_Username","loginTestINPass"},
{"loginTestJP_UserName","loginTestJPPass"}
};
return data;
}
@SetTestName(idx=0)
@Test(dataProvider="userData")
public void test1(String userName, String pass)
{
System.out.println("Testcase 1");
}
@SetTestName(idx=1)
@Test(dataProvider="userData")
public void test2(String userName, String pass)
{
System.out.println("Testcase 2");
}
It's all. You will now see your test name changed accordingly in the console.
Follow the link below for your request. Hope you can get your answer here:
http://biggerwrench.blogspot.com/2014/02/testng-dynamically-naming-tests-from.html
source to share
Example for reference.
- Use this line for example
"USusername"
etc. in your data provider (like"TestName1"
and"TestName2"
in the example) along with some other test data (like these numbers in the example). Pass this name as an argument to your annotated method@Factory
. - Make a test class class
ITest
. Use the test name variable in the return statement. - You can break it like in the example.
source to share