I have this in my parent class to set the testName attribute. Note that the TestMethod might be either a normal testcase or dataprovider (with using spreadsheet or one where the dataprovider is directly defined in the testclass) or invocation count testcase. Hence I have so many if else clauses:
@BeforeMethod(alwaysRun=true)
public void setUpTest(Method method, Object[] testData, ITestContext ctx) {
log.info("BeforeMethod from BaseTestSection");
try {
Map<String,String> map = new HashMap<String,String>();
//For tests that use invocation count
//TODO
//For data-provider tests
if (testData.length > 0) {
/*Check if testData is coming from spreadsheet(converted to comma separated values)
or from a dataprovider class(no comma present)*/
if(testData[0].toString().contains(",")) { //For data-providers that use spreadsheets
String[] entries = testData[0].toString().replace("{","").replace("}","").split(",");
//For each
if(entries.length>1) {
for(String entry:entries) {
map.put(entry.split("=")[0].trim(), entry.split("=")[1].trim());
}
TestID = map.get("TestID");
}
//Certain spreadsheets like DefaultSessionStimulationTestData does not contain TestID's
if(TestID == null) {
testName.set(method.getName());
ctx.setAttribute("testName", method.getName());
}else {
testName.set(method.getName() + "_" + TestID);
ctx.setAttribute("testName", method.getName() + "_" + TestID);
}
}
else if(!testData[0].toString().contains(",")) { //For data-providers that don't use spreadsheets
TestID = testData[0].toString();
testName.set(method.getName() + "_" + TestID);
ctx.setAttribute("testName", method.getName() + "_" + TestID);
}
else { //Code used for dataproviders that have single entry and no TestID's, viz create_patient
testName.set(method.getName() + "_" + testData[0].toString());
ctx.setAttribute("testName", method.getName() + "_" + testData[0].toString());
}
}
else //For non-dataprovider tests
{
TestID = method.getName();
testName.set(method.getName());
ctx.setAttribute("testName", method.getName());
}
log.info("Testname in BaseTestSection is: " + ctx.getAttribute("testName"));
//Also check if app is already running. Helpful in conditions where app shutsdown in middle of any testcase though setup was completed successfully
if (!setupComplete && driver!=null){
log.info("Relaunching app if setup incomplete. This also helps with picking up the cp.configuration.json file if setup in beforeClass method...");
try {
driver.launchApp();
beforeEachTestMethod();
}catch(Exception e) {
e.printStackTrace();
throw new Exception();
}
}
setupComplete=true;
}catch(Exception e) {e.printStackTrace();}
}