TestNG run set of test cases in loop - java

Searched everywhere but could not find solution how to do following:
As Example:
for (int i = 0; i < 5; i++) {
#Test
public void test1(){
assertThat(assertvalue 1);
}
#Test
public void test2(){
assertThat(assertvalue 2);
}
#Test
public void test3(){
assertThat(assertvalue 3);
}
}
Of course I can use dataProvider or invocationCount and do all asserts in one test case, but if one assert will fail whole test case fail. I want kind of separate one big test case for 3 small test cases
Any help appreciated

Having dependencies between test cases is discouraged. You could achieve a similar result--checking each value 1-5 without short-circuiting and stopping after a failure on 2--using SoftAssert.
SoftAssert soft = new SoftAssert();
soft.fail("Failure # 1\n");
soft.fail("Failure # 2");
soft.assertAll();
should output:
The following assertions failed:
Failure # 1
Failure # 2

I tried following code:
public class SimpleTest {
private String param = "";
public SimpleTest(String param) {
this.param = param;
}
#BeforeClass
public void beforeClass() {
System.out.println("Before SimpleTest class executed.");
}
#Test
public void testMethod1() {
System.out.println("testMethod parameter value is: " + param);
}
#Test(dependsOnMethods = "testMethod1")
public void testMethod2() {
System.out.println("testMethod parameter value is: " + param);
}
}
public class SimpleTestFactory{
#Factory
public Object[] factoryMethod() {
return new Object[] {
new SimpleTest("one"),
new SimpleTest("two")
};
}
And tried following code and it does not keep order

Add invocationCount
#Test(priority = 350, groups = "success" ,invocationCount = 10)
public void test1(){
assertThat(assertvalue 1);
}

Use "property",if you want to execute test1(),add "priority =1"
#Test
public void test1(priority =1){
System.out.println("execute frist");;
}
#Test
public void test2(priority =2){
assertThat(assertvalue 2);
}
#Test
public void test3(priority =3){
assertThat(assertvalue 3);
}

#Test
public void main() throws IOException,InterruptedException
{
FileInputStream fil = new FileInputStream(new File("C:\\Users\\V-DKumaravelu\\ECM Data\\ECM-Data-Sheet.xlsx"));
XSSFWorkbook workbook=new XSSFWorkbook(fil);
XSSFSheet sheet=workbook.getSheet("ECM");
int count=sheet.getLastRowNum();
System.out.println(count);
for (int i=1;i<=5;i++){
Snapshot sc = new Snapshot();
XSSFRow row = sheet.getRow(i);
XSSFCell cell = row.getCell(0);
String ServiceDate=cell.getStringCellValue();
System.out.println("DOSate is "+ ServiceDate);
XSSFCell cell1=row.getCell(1);
String MemberID=cell1.getStringCellValue();
System.out.println("Member "+MemberID);
XSSFCell cell2 = row.getCell(2);
String FacilityCode=cell2.getStringCellValue();
System.out.println("Facility Code "+FacilityCode);
XSSFCell cell3=row.getCell(3);
String ReleaseOfInfo=cell3.getStringCellValue();
System.out.println("ROI " + ReleaseOfInfo);
XSSFCell cell4 = row.getCell(4);
String ContactName=cell4.getStringCellValue();
System.out.println("Contact Name " + ContactName);
XSSFCell cell5=row.getCell(5);
String ContactPhoneAreaCode=cell5.getStringCellValue();
System.out.println("ContactPhoneAreaCode " + ContactPhoneAreaCode);
XSSFCell cell6 = row.getCell(6);
String ContactPhonePrefix=cell6.getStringCellValue();
System.out.println("ContactPhoePrefix " + ContactPhonePrefix);
XSSFCell cell7=row.getCell(7);
String ContactPhoneLine=cell7.getStringCellValue();
System.out.println("ContactPhoneLine " + ContactPhoneLine);
XSSFCell cell8=row.getCell(8);
String ContactPhoneExt=cell8.getStringCellValue();
System.out.println("ContactPhoneExt " + ContactPhoneExt);
XSSFCell cell9 = row.getCell(9);
String ServiceType=cell9.getStringCellValue();
System.out.println("ServiceType " + ServiceType);
XSSFCell cell10=row.getCell(10);
String ServiceLevel=cell10.getStringCellValue();
System.out.println("ServiceLevel " + ServiceLevel);
XSSFCell cell11=row.getCell(11);
String PRIS=cell11.getStringCellValue();
System.out.println("PRIS " + PRIS);
XSSFCell cell12 = row.getCell(12);
String DiagnosisCode=cell12.getStringCellValue();
System.out.println("Diagosis " + DiagnosisCode);
XSSFCell cell13=row.getCell(13);
String ProcedureCode=cell13.getStringCellValue();
System.out.println("Procedure Code " + ProcedureCode);
XSSFCell cell14=row.getCell(14);
String unitsProcedure=cell14.getStringCellValue();
System.out.println("Procedure Units " + unitsProcedure);
System.setProperty("webdriver.chrome.driver", "C:\\Users\\V-DKumaravelu\\eclipse-workspace\\ECM Portal\\driver\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://10.32.52.79:8888/ECM/clientlogin.aspx");
driver.findElement(By.id("txtUserId")).sendKeys("203861P");
driver.findElement(By.id("txtPassword")).sendKeys("RETINA01");
driver.findElement(By.id("btnLogin")).click();
driver.findElement(By.xpath("//*[#id=\'_ctl7_lbNewPA\']")).click();
driver.findElement(By.id("outpatientServices2")).click();
driver.findElement(By.id("serviceDate")).sendKeys(ServiceDate);
driver.findElement(By.id("memberID")).sendKeys(MemberID);
sc.main(driver);
driver.findElement(By.id("nextLink1")).click();
Select select = new Select(driver.findElement(By.id("facilityCode")));
select .selectByVisibleText(FacilityCode);
Select select1 = new Select(driver.findElement(By.id("releaseOfInfo")));
select1 .selectByVisibleText(ReleaseOfInfo);
driver.findElement(By.id("ContactName")).sendKeys(ContactName);
driver.findElement(By.id("ContactPhoneAreaCode")).sendKeys(ContactPhoneAreaCode);
driver.findElement(By.id("ContactPhonePrefix")).sendKeys(ContactPhonePrefix);
driver.findElement(By.id("ContactPhoneLine")).sendKeys(ContactPhoneLine);
driver.findElement(By.id("ContactPhoneExt")).sendKeys(ContactPhoneExt);
sc.main(driver);
driver.findElement(By.id("nextLink1")).click();
Select select2 = new Select(driver.findElement(By.xpath("//*[#id='serviceType']")));
select2 .selectByVisibleText(ServiceType);
Select select3 = new Select(driver.findElement(By.xpath("//*[#id=\'levelOfService\']")));
select3 .selectByVisibleText(ServiceLevel);
driver.findElement(By.id("facilityPris")).sendKeys(PRIS);
driver.findElement(By.id("diagnosisCode")).sendKeys(DiagnosisCode);
driver.findElement(By.id("addDiagnosis")).click();
driver.findElement(By.id("codeProcedure")).sendKeys(ProcedureCode);
driver.findElement(By.id("unitsProcedure")).sendKeys(unitsProcedure);
driver.findElement(By.id("addProcedure")).click();
sc.main(driver);
driver.findElement(By.id("nextLink2")).click();
driver.findElement(By.id("btnSubmit")).click();
sc.main(driver);
Assert.assertNotNull(driver.findElement(By.xpath("//*[#id=\'Table1\']/tbody/tr[5]/td[6]")),"Failed");
driver.close();
}}
}

Related

Why is the constructor not taking a value passed during object creation?

I am writing a code wherein I am operating with an excel file having three sheets. I am using Apache POI and Data provider annotation for data driven approach. I wanted to pass Sheet index number or Sheet name at run time but I was not able to do it setting a parameter to data provider method. So what I did is I wrote a constructor and a static variable as integer. In parameterized constructor, I initialized that static variable and then in my test case, by creating object of the class which had data provider method, I passed an integer that is, sheet index from which I wanted the data to be taken to run the test. But every time, the constructor is taking value as 0. I don't know why. Below is the data driven code and constructor I have written.
public class Excel_Util {
static int fileinitial;
public Excel_Util(int filename) {
fileinitial=filename;
}
#DataProvider(name="testdata")
public static Object[][] readexcelretobj() throws Exception {
FileInputStream f= new FileInputStream("F:\\Eclipse Java new Programs\\shdtestpeopleinteractive\\src\\test\\resources\\Test_data.xls");
HSSFWorkbook workbook = new HSSFWorkbook(f);
HSSFSheet s = workbook.getSheetAt(fileinitial);
HSSFRow row = s.getRow(0);
int rownum=s.getPhysicalNumberOfRows();
int colnum=row.getLastCellNum();
//System.out.println(rownum);
//System.out.println(colnum);
Object data[][] = new Object[rownum][colnum];
List<Object> l = new ArrayList<Object>();
for(int i=0;i<rownum-1;i++) {
row = s.getRow(i+1);
for(int j=0;j<colnum;j++) {
HSSFCell c = row.getCell(j);
//l.add(c.getStringCellValue());
data[i][j]=c.getStringCellValue();
}
}
return data;
}
The test case which I wrote is as follows.
#Test(dataProvider="testdata",dataProviderClass=Excel_Util.class)
public void testsignupdatafields(String email, String password) {
Syncutil.Implicitwait();
try {
Excel_Util ex = new Excel_Util(2);
getdriver().get("https://www."+csvreaderutil.csvread().get(0).toString()+"/");
Marathishd marathishdpage = PageFactory.initElements(getdriver(), Marathishd.class);
Signuppagemarathishd signup = marathishdpage.letsbeginclick();
signup.emailid.sendKeys(email);
signup.password.sendKeys(password);
}catch(Exception e) {System.out.println("Exception");}
}
}
Here, I have passed 2 at the time of object creation but every time, the values are taken from the first sheet. That is, sheet index 0 is considered every time. I don't want to hard code any value in excelutil class code as I wanted to behave it as generic code. So in test case itself I decided to pass sheet number. I am confused what to do and wanted a reason why this is happening and what is the mistake I am doing. Can anyone please guide me with this ?
I simplified the code to replicate the issue.
Existing code :
#Test method:
#Test(dataProvider = "testdata", dataProviderClass = Excel_Util.class)
public void testsignupdatafields(String email, String password) {
System.out.println("Test started");
new Excel_Util(2);
System.out.println("Email: " + email + " & Passowrd: " + password);
}
Excel_Util:
public class Excel_Util {
static int fileinitial;
public Excel_Util(int filename) {
fileinitial = filename;
System.out.println("Constructor called...");
System.out.println("Sheet number: " + fileinitial);
}
#DataProvider(name = "testdata")
public static Object[][] readexcelretobj() throws Exception {
Object[][] object = new Object[1][2];
object[0][0] = "Nandan";
object[0][1] = "123456";
System.out.println("Data provider called...");
System.out.println("Sheet number: " + fileinitial);
return object;
}
}
Output:
Data provider called...
Sheet number: 0
Test started
Constructor called...
Sheet number: 2
Email: Nandan & Passowrd: 123456
If you see the above output the DataProvider code is being called first so your value is passing as 0. To fix this call the new Excel_Util(2); object into DataProvider
Updated code :
#Test method:
#Test(dataProvider = "testdata", dataProviderClass = Excel_Util.class)
public void testsignupdatafields(String email, String password) {
System.out.println("Test started");
System.out.println("Email: " + email + " & Passowrd: " + password);
}
Excel_Util:
public class Excel_Util {
static int fileinitial;
public Excel_Util(int filename) {
fileinitial = filename;
System.out.println("Constructor called...");
System.out.println("Sheet number: " + fileinitial);
}
#DataProvider(name = "testdata")
public static Object[][] readexcelretobj() throws Exception {
new Excel_Util(2);
Object[][] object = new Object[1][2];
object[0][0] = "Nandan";
object[0][1] = "123456";
System.out.println("Data provider called...");
System.out.println("Sheet number: " + fileinitial);
return object;
}
}
Output:
Constructor called...
Sheet number: 2
Data provider called...
Sheet number: 2
Test started
Email: Nandan & Passowrd: 123456
If you see the above output now the constructor is being called first.
Solution#1:
As we discussed if you want to pass the value from Test class then you can do something like this. Instead of a constructor use static block.
Test class:
public class ClassTestNG {
static int sheetNumber = 2;
#Test(dataProvider = "testdata", dataProviderClass = Excel_Util.class)
public void testsignupdatafields(String email, String password) {
System.out.println("Test started");
System.out.println("Email: " + email + " & Passowrd: " + password);
}
Excel_Util:
public class Excel_Util {
static int fileinitial;
static {
fileinitial = ClassTestNG.sheetNumber;
System.out.println("Static called...");
System.out.println("Sheet number: " + fileinitial);
}
#DataProvider(name = "testdata")
public static Object[][] readexcelretobj() throws Exception {
Object[][] object = new Object[1][2];
object[0][0] = "Nandan";
object[0][1] = "123456";
System.out.println("Data provider called...");
System.out.println("Sheet number: " + fileinitial);
return object;
}
}
Output:
Static called...
Sheet number: 2
Data provider called...
Sheet number: 2
Test started
Email: Nandan & Passowrd: 123456
Solution#2:
You can use #BeforeTest annotation as well.
Test class:
#BeforeTest
public void passSheetNumber() {
new Excel_Util().assignSheetNumber(2);
}
#Test(dataProvider = "testdata", dataProviderClass = Excel_Util.class)
public void testsignupdatafields(String email, String password) {
System.out.println("Test started");
System.out.println("Email: " + email + " & Passowrd: " + password);
}
Excel_Util:
public class Excel_Util {
static int fileinitial;
public void assignSheetNumber(int sheetNumber) {
fileinitial = sheetNumber;
System.out.println("Sheet number: " + fileinitial);
}
#DataProvider(name = "testdata")
public static Object[][] readexcelretobj() throws Exception {
Object[][] object = new Object[1][2];
object[0][0] = "Nandan";
object[0][1] = "123456";
System.out.println("Data provider called...");
System.out.println("Sheet number: " + fileinitial);
return object;
}
}
Output:
Sheet number: 2
Data provider called...
Sheet number: 2
Test started
Email: Nandan & Passowrd: 123456
fileinitial=filename;
It's a wonder you did not get an error message about a static int cannot be assigned from a non static context!
Why not simply take static off your global fileinitial.
*NB the class with the int problem were the main class and if you were calling from public static void main(String args[]) that would be different and not require assigning by the constructor, so if it is not the main class remove static keyword from variable "fileinitial".
Or build a static class (always nested subclass) to send the "non static filename argument" into (through) a static method and return it as static assignment from that method.

NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file - UNIT TEST Spring

I am trying to unit test this piece of code:
#Slf4j
#Service
#RequiredArgsConstructor
public class LeMigrationService {
private final MigrationServiceClient migrationServiceClient;
public FileUploadRs process(MultipartFile file) {
List<String> listOfCifs = null;
try {
listOfCifs = ExcelUtil.collectColumnByIndex(file, 0);
} catch (Exception e) {
LOGGER.error("Failed to load excel file content " + e);
}
return migrationServiceClient.process(listOfCifs);
}
}
The static method:
public class ExcelUtil {
public static List<String> collectColumnByIndex(MultipartFile file, int index) throws Exception {
List<String> listOfCifs = new ArrayList<>();
Workbook workbook = new XSSFWorkbook(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Cell cell = row.getCell(index);
int cellLength = cell.getStringCellValue().length();
if (cellLength < 9) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 9 - cellLength; i++) {
str.append("0");
}
str.append(cell.getStringCellValue());
listOfCifs.add(str.toString());
}
if (cellLength > 9) {
break;
}
if(cellLength == 9) {
listOfCifs.add(cell.getStringCellValue());
}
}
return listOfCifs;
}
}
And finally my unit test:
#RunWith(MockitoJUnitRunner.class)
public class LeMigrationServiceTest {
#Test
public void processFile_FileContentIsOk() throws Exception{
//arrange
final MockMultipartFile fakeFile = new MockMultipartFile("file", "file.xls", MediaType.TEXT_PLAIN_VALUE, "0123456789".getBytes());
//act
final List<String> actual = ExcelUtil.collectColumnByIndex(fakeFile, 0);
final List<String> expected = new ArrayList<>();
expected.set(0, "0123456789");
//assert
assertThat(actual).isEqualTo(expected);
}
}
When I run the test, I get the error when it calls the static method "collectColumnByIndex". Apparently I do not create well the object "Workbook" inside the method "collectColumnByIndex". Do you have any ideas of how to solve this?

Selenium java Maven how to execute Testcase with fillo qry data driven framework

Testcase file. Testcase with fillo query data driven
Suppose when the query (String qry="Select * from Sheet1 where ACC='M' and GEN='F'";) returns 5 data rows for one test case and i want to use the same qry for the next case but with different data row
public class Testcases {
public WebDriver driver;
Fillo fillo;
static ExtentReports report;
ExtentTest test;
//String PAGE_URL = "Your_page_Url";
#BeforeClass public static void allTestsPrep(){
report = new ExtentReports("Report.html",true);
}
#AfterClass public static void allTestCleanUp() {
report.flush();
}
#Before
public void setUp() {
String browserName = getParameter("browser");
if (browserName.equalsIgnoreCase("chrome")){
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();}
else if (browserName.equalsIgnoreCase("ie")) {
driver = new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// driver.get(PAGE_URL);
}
#Test
public void Testcase001() throws FilloException, InterruptedException {
String qry="Select * from Sheet1 where ACC='M' and GEN='F'";
test = report.startTest("Testcase 1 - Test findpage");
Useragreement usragr = new Useragreement(driver);
usragr.CheckboxSelectall();
test.log(LogStatus.PASS, "VERIFIED");//report
}
#After
public void close() {
driver.close();
test = null;
}
private String getParameter(String name) {
String value = System.getProperty(name);
if (value == null)
throw new RuntimeException(name + " is not a parameter!");
if (value.isEmpty())
throw new RuntimeException(name + " is empty!");
return value;
}
}
Fillo file
Now the code will be `FILLO.inputText(Phone_Number,"Pno",qry)``;
public class FILLOAPP {
public static String getTestValue(String fieldName, String qry) throws FilloException{
String testString=xlTesting(fieldName,qry);
return testString;
}
public static String xlTesting(String fieldName, String qry) throws FilloException{
String testval=null;
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("resources/TestData.xlsx");
String sqry=qry;
Recordset recordset=connection.executeQuery(sqry);
while(recordset.next()){
ArrayList<String> dataColl=recordset.getFieldNames();
Iterator<String> dataIterator=dataColl.iterator();
while(dataIterator.hasNext()){
for (int i=0;i<=dataColl.size()-1;i++){
String data=dataIterator.next();
String dataVal=recordset.getField(data);
if (data.equalsIgnoreCase(fieldName)){
String testData=dataColl.get(i);
String testValue= recordset.getField(testData);
testval=testValue;
}
}
break;
}
}
recordset.close();
connection.close();
return testval;
}
public static void inputText(WebElement driver, String fieldName, String qry) throws FilloException{
String fval=getTestValue(fieldName, qry);
driver.sendKeys(fval);
}
}
public String dataRead(String sheetname, String testcaseid, String header) throws IOException {
String value = null;
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
book = new XSSFWorkbook(fis);
sheet = book.getSheet(sheetname);
int lastRowNum = sheet.getLastRowNum();
// System.out.println(lastRowNum);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(lastCellNum);
for (int i = 0; i < lastRowNum; i++) {
for (int j = 1; j < lastCellNum; j++) {
Map<String, Map<String, String>> excelmap = new HashMap<String, Map<String, String>>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i + 1).getCell(j).toString());
excelmap.put(sheet.getRow(i + 1).getCell(0).toString(), map);
if (excelmap.containsKey(testcaseid)) {
Map<String, String> w = excelmap.get(testcaseid);
if (map.containsKey(header)) {
value = w.get(header).toString();
}
}
}
}
} catch (Exception E) {
}
return value;
}
public void excelWrite(String sheetname, String testcaseid, int columnno, String value) throws Throwable {
File file = new File(TESTDATA_SHEET_PATH);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetname);
// sheetnoOfColumns = sheet.getRow(0).getPhysicalNumberOfCells();
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i < lastRowNum; i++) {
Map<Map<String, String>, String> excelmap = new HashMap<Map<String, String>, String>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(0).toString(), sheet.getRow(i + 1).getCell(0).toString());
if (map.containsValue(testcaseid)) {
excelmap.put(map, value);
String w = map.get("TestCase ID");
Map<String, String> fin = new HashMap<String, String>();
fin.put(w, value);
XSSFRow row = sheet.getRow(i + 1);
Cell createcell = row.createCell(columnno);
createcell.setCellValue(value);
}
}
FileOutputStream fileOut = new FileOutputStream(TESTDATA_SHEET_PATH);
workbook.write(fileOut);
fis.close();
fileOut.close();
}
public Map ReadExcelExecution() throws Throwable {
LinkedHashMap<String, Object[]> map = new LinkedHashMap<String, Object[]>();
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("IssuePolicy");
int TotalRow = sheet.getLastRowNum();
int noOfColumns = (sheet.getRow(0).getPhysicalNumberOfCells() - 1);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(TotalRow);
// System.out.println(noOfColumns);
// System.out.println(lastCellNum);
map.put("1",
new Object[] { "TestCase ID", "PolicyNo", "IssueDate", "Accumulated Value", "GMWB Type",
"MAWA/2LMAWA", "Remaining MAWA", "Protected Income Payment", "Accumulated Value DOD",
"DataComparison", "Comments" });
for (int i = 1; i <= TotalRow; i++) {
{
String testcaseid = sheet.getRow(i).getCell(0).toString();
String policyno = sheet.getRow(i).getCell(noOfColumns).toString();
String issuedate = sheet.getRow(i).getCell(2).toString();
String values = null;
map.put(testcaseid, new Object[] { testcaseid, policyno, issuedate, values, values, values, values,
values, values, values, values });
}
}
} catch (Exception E) {
}
return map;
}
public void writinginInputFile(String sheetname, Map mapvalue) throws Throwable {
// write excel file and file name is SaveTestNGResultToExcel.xls
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.createSheet(sheetname);
keyset = mapvalue.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = (Object[]) ReadExcelExecution().get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(TESTDATA_SHEET_PATH));
wb.write(out);
out.close();
System.out.println("Successfully saved Selenium WebDriver TestNG result to Excel File!!!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
}
package seleniumproject;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Multiplewindowpopup {
public static void main(String[] args) {
WebDriver driver;
String Userdir = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",Userdir+"\\Driver\\chromedriver.exe");
driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("http://www.popuptest.com/goodpopups.html");
//find ID of the 2nd link
driver.findElement(By.linkText("Good PopUp #2")).click();
Set<String> windowhandler = driver.getWindowHandles();
Iterator<String> myiterator = windowhandler.iterator();
////////////// //how to get index of parent and child window ???
//now we have two window IDs and moving the window from parent to child.
driver.switchTo().window(childWindow);
System.out.println("child window title"+driver.getTitle());
//closing the child window
driver.close();
// comming back to parentwindow
driver.switchTo().window(parentWindow);
System.out.println("parent window title"+driver.getTitle());
}
}

Why webdriver continuously open for each operation?

I am beginner in Selenium, there are two separate .xls file file one for GmailTestSuite.xls and other for objectrepository.xls.
I have created MainClass, in it I have written a code which read both .xls file, also I've open the driver in it and perform operation. But problem is that it continuously open new driver but don't perform any operation.
Please suggest and let me know where I'm going wrong.
public class MainClass {
static Properties properties= null;
public static void main(String[] args) throws IOException, BiffException{
// TODO Auto-generated method stub
ReadPropertyFile readConfigFile= new ReadPropertyFile();
properties= readConfigFile.loadPropertiess();
ExcelHandler testSuite= new ExcelHandler("D:\\GmailTestSuite.xls", "Suite");
testSuite.columnData();
int rowCount= testSuite.rowCount();
System.out.println("Total Rows="+rowCount);
for(int i=1;i<rowCount;i++)
{
String executable= testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable="+executable);
if(executable.equalsIgnoreCase("y")){
// exe. the process
String scenarioName= testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name="+scenarioName);
ExcelHandler testScenarios= new ExcelHandler("D:\\GmailTestSuite.xls", scenarioName);
int rowWorkBook1= testScenarios.rowCount();
for(int j=1; j<rowWorkBook1;j++){
String framWork= testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); //SendKey
String value= testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMName="+framWork+",Operation="+operation+",Value="+value);
ExcelHandler objectRepository= new ExcelHandler("D:\\objectrepository.xls", "OR");
objectRepository.columnData();
int rowCount1= testSuite.rowCount();
System.out.println("Total Rows="+rowCount1);
for(int k=1;k<rowCount;k++){
String frameWorkName= objectRepository.readCell(objectRepository.getCell("Executable"), k);
String ObjectName= objectRepository.readCell(testScenarios.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(testScenarios.getCell("Locator"), k); //SendKey
System.out.println("FrameWorkName="+frameWorkName+",ObjectName="+ObjectName+",Locator="+Locator);
//ExcelHandler executeOperation = new ExcelHandler(ObjectName, operation, value);
File file= new File("D:\\softs\\FF installed\\FF18\\firefox.exe");
FirefoxBinary fb = new FirefoxBinary(file);
WebDriver driver = new FirefoxDriver(fb,new FirefoxProfile());
driver.get("https://www.gmail.com");
WebElement we = driver.findElement(By.id("Email"));
if(operation.equalsIgnoreCase("SendKey"))
{
we.sendKeys("abc#gmail.com");
we.sendKeys("si#2013");
}
if(operation.equalsIgnoreCase("Click"))
we.click();
}
}
}
}
}
A couple of guide lines for better formed code:
Break your code into methods that only do one thing each. That way it's easier to manage and nicely compartmentalized, plus you don't enter into indentation hell with such embedded loop and if structures as the one you have over here.
Use class variables for things like the WebDriver instance, so you can initialize it once and keep calling on it later.
Don't hard code text into the application, use constants. Then you only need to define the text once and can refer to it multiple times. Makes the code much easier to maintain and change, when you don't have to search and replace through entire class, after some details (like a file path) change.
Also, I'm guessing you meant to do the following:
loop the rows in objectRepository in the k-loop, instead of looping the rows in the testSuite again.
get cells from objectRepository rather than from testScenarios when reading the cells from objectRepository
Example:
public class MainClass {
private static final String BROWSER_PATH = "D:\\softs\\FF installed\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
private static final By EMAIL_INPUT = By.id("Email");
// other constants
private WebDriver driver;
private Properties properties;
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
}
private void handleScenario(String scenarioName) {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH, scenarioName);
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMName=" + framWork + ",Operation=" + operation +
",Value=" + value);
handleObjects(operation);
}
}
private void handleObjects(String operation) {
ExcelHandler objectRepository = new ExcelHandler(OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(objectRepository.getCell("Executable"), k);
String ObjectName = objectRepository.readCell(objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkName=" + frameWorkName +
",ObjectName=" + ObjectName + ",Locator=" + Locator);
operateWebDriver(operation);
}
}
private void operateWebDriver(String operation) {
WebElement we = driver.findElement(EMAIL_INPUT);
if (operation.equalsIgnoreCase("SendKey")) {
we.sendKeys("abc#gmail.com");
we.sendKeys("si#2013");
} else if (operation.equalsIgnoreCase("Click")) {
we.click();
}
}
}
If ExcelHandler is your own implementation, you really should move the getCell(String s) method inside the readCell() method to change the call pattern of handler.readCell(handler.getCell("foo"), i) into handler.readCell("foo", i). If it's a library you're using, you can always make a helper method:
private static String readCell(ExcelHandler handler, String cellName, int row) {
return handler.readCell(handler.getCell(cellName), row);
}
EDIT
Since you're having problems with getting WebDriver to work, simplify things and take everything else out of the equation for now. In order to do that let's ignore all the reading data from .xls files. This is where having different methods for different things makes your design shine, since you can just comment one method call instead of having to comment out 50 lines of code from your one mega method.
Changed the above code a bit (just commented call to the other methods out and omitted them from the snippet, moved the line opening the correct page into constructor and rewrote the operateWebDriver() method a bit):
public class MainClass {
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
private static final By EMAIL_INPUT = By.id("Email");
private static final By PASSWORD_INPUT = By.id("Passwd");
private static final By SIGN_IN_BUTTON = By.id("signIn");
private static final String EMAIL = "test#abc.com";
private static final String PASSWORD = "test123";
private WebDriver driver;
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
//main.handleTestSuite();
main.operateWebDriver("Click", EMAIL_INPUT);
main.operateWebDriver("SendKey", EMAIL_INPUT, EMAIL);
main.operateWebDriver("Click", PASSWORD_INPUT);
main.operateWebDriver("SendKey", PASSWORD_INPUT, PASSWORD);
main.operateWebDriver("Click", SIGN_IN_BUTTON);
}
private void operateWebDriver(String operation, By element) {
operateWebDriver(operation, element, null);
}
private void operateWebDriver(String operation, By element, String keys) {
WebElement we = driver.findElement(element);
if (operation.equalsIgnoreCase("SendKey")) {
we.sendKeys(keys);
} else if (operation.equalsIgnoreCase("Click")) {
we.click();
}
}
}
Then once you get WebDriver working, you can start reading the data from the files and using it to operate WebDriver.
#user2092132- You require to make changes on two places in your code
1: Insert new line after line- System.out.println("Total Rows="+rowCount);
WebDriver driver = null;
2:Change line from: WebDriver driver = new FirefoxDriver(fb,new FirefoxProfile());
To: driver = new FirefoxDriver(fb,new FirefoxProfile());
Above two changes should resolve initiating new instacne of FF each time.

How to run multiple tests in one instance of driver

I have the following code, I am extracting data from excel sheet and filling web form. Its a registration form and its registering two users. But once the second test runs, it starts another instance of driver. May I know how to do it in one instance.
#RunWith(Parameterized.class)
public class form {
private static WebDriver driver;
private String first;
private String last;
private String phone;
private String country;
private String about;
public form(String first, String last, String phone, String country, String about)
{
this.first = first;
this.last = last;
this.phone = phone;
this.country = country;
this.about = about;
}
#Before
public void before()
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Parameters
public static Collection<Object[]> supplydata() throws IOException
{
File excel = new File("C:\\Users\\Master\\Desktop\\search_query_log.xls");
FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Sheet1");
int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
Object[][] data = new Object[rowNum][colNum];
for (int i=0; i < rowNum ; i++)
{
HSSFRow row = ws.getRow(i);
for(int j=0; j < colNum ; j++)
{
HSSFCell cell = row.getCell((short) j);
if(cell.getCellType()==cell.CELL_TYPE_STRING)
{
data[i][j]=cell.getStringCellValue();
}
else if(cell.getCellType()==cell.CELL_TYPE_NUMERIC)
{
data[i][j]=String.valueOf(cell.getNumericCellValue());
}
}
}
return Arrays.asList(data);
}
#Test
public void testcase() throws IOException, InterruptedException
{
driver.get("http://www.samplereg.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("fname")).sendKeys(first);
driver.findElement(By.name("lastname")).sendKeys(last);
driver.findElement(By.name("phonenumber")).sendKeys(phone);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement gender = driver.findElement(By.xpath("//input[#value='Male']"));
if (!gender.isSelected())
gender.click();
assertTrue(gender.isSelected());
driver.findElement(By.name("country")).sendKeys(country);
driver.findElement(By.name("desc")).sendKeys(about);
Select industry = new Select(driver.findElement(By.name("industry")));
assertFalse(industry.isMultiple());
assertEquals(6, industry.getOptions().size());
List<String> exp_options = Arrays.asList(new String[]{"Select Industry", "IT", "BPO","Sales","Development","Other"});
List<String> act_options = new ArrayList<String>();
for(WebElement option : industry.getOptions())
act_options.add(option.getText());
assertArrayEquals(exp_options.toArray(),act_options.toArray());
assertEquals("Select Industry", industry.getFirstSelectedOption().getText());
industry.selectByVisibleText("BPO");
assertEquals("BPO", industry.getFirstSelectedOption().getText());
Select education = new Select(driver.findElement(By.name("educationList")));
assertFalse(education.isMultiple());
assertEquals(4, education.getOptions().size());
List<String> exp_options1 = Arrays.asList(new String[]{"Select Education", "Post Graduate", "Graduate", "Under Graduate"});
List<String> act_options1 = new ArrayList<String>();
for(WebElement option1 : education.getOptions())
act_options1.add(option1.getText());
assertArrayEquals(exp_options1.toArray(),act_options1.toArray());
assertEquals("Select Education", education.getFirstSelectedOption().getText());
education.selectByVisibleText("Graduate");
assertEquals("Graduate", education.getFirstSelectedOption().getText());
WebElement hobby = driver.findElement(By.xpath("//input[#value='Listening Music']"));
if (!hobby.isSelected())
hobby.click();
assertTrue(hobby.isSelected());
driver.findElement(By.cssSelector("input[type=file]")).sendKeys("C:\\Users\\Master\\Desktop\\image.jpg");
driver.findElement(By.cssSelector("input[type=submit]")).click();
}
#After
public void after()
{
//driver.quit();
}
}
How about trying the below. Hope my understanding is correct.
#BeforeClass
public static void setUpClass() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
Alert javascriptAlert = driver.switchTo().alert();
System.out.println(javascriptAlert.getText()); // Get text on alert box
javascriptAlert.accept(); // Chose whether to accept or cancel based on need
}
You can remove the #before method.

Categories