In Flash page Select box (combobox) is not working using Webdriver - java

I have done some sample code to select a combobox using webdriver in a Flash page but Select(...) and type(....) methods are not working but click(....) method works fine.
Please help to resolve this.
Type-1: Below methods are not working.
public void type(String locator, String value)
{
((JavascriptExecutor) webDriver).executeScript("document.getElementById('" + flashObjectId + "').fp_type({" + locator +", 'text':'"+ value +"'})");
}
public void select(String locator, String value)
{
((JavascriptExecutor) webDriver).executeScript("document.getElementById('" + flashObjectId + "').fp_select({" + locator +", 'label':'"+ value +"'})");
}
Its working fine in below click(....) method.
public String click(final String objectId, final String optionalButtonLabel)
{
return call("doFlexClick", objectId, optionalButtonLabel);
}
private String call(final String functionName, final String... args)
{
final Object result =
((JavascriptExecutor)webDriver).executeScript(
makeJsFunction(functionName, args),
new Object[0]);
return result != null ? result.toString() : null;
}
private String makeJsFunction(final String functionName, final String... args)
{
final StringBuffer functionArgs = new StringBuffer();
if (args.length > 0)
{
for (int i = 0; i < args.length; i++)
{
if (i > 0)
{
functionArgs.append(",");
}
functionArgs.append(String.format("'%1$s'", args[i]));
System.out.println("functionArgs: "+functionArgs);
}
}
return String.format(
"return document.%1$s.%2$s(%3$s);",
flashObjectId,
functionName,
functionArgs);
}
Please help to fix this in select box and tyep operation using webdriver in Flash.
Thanks in Advance,
Gopal

Watir-Webdriver does not support flash pages.

Related

How to pass the global variable from one Test class to another test class and select that value in a dropdown in selenium?

I have this class ( DoctorRegistrationTest.java ) and having the global variable doctorCode , doctorFirstName , doctorFamilyName )
#BeforeMethod(groups = {"BVT", "Regression"})
public void loadRmsPage() {
loadRmsProfile();
softAssert = new SoftAssert();
doctorRegistrationPage = new DoctorRegistrationPage(webDriver);
}
#Epic("RMS - Create Doctor")
#Feature("RMS - Create Doctor functionality")
#Story("AUT-688")
#Severity(SeverityLevel.BLOCKER)
#Test(description = "Positive : Doctor Creation ", groups = {"BVT", "Regression"})
public void createDoctorTestMethod() {
do {
doctorCode = String.valueOf(generateRandomNumber(1000, 9999));
} while (false && doctorRegistrationPage.verifyCreatedDoctor(doctorCode));
setDoctorRegistrationInformation();
createDoctor();
}
public void createDoctor() {
doctorRegistrationPage.loadDoctorRegistrationPage();
doctorRegistrationPage.fillDoctorNameInformation(doctorCode, doctorFirstName, doctorFamilyName, doctorFirstNameInArabic, doctorFamilyNameInArabic);
doctorRegistrationPage.fillDoctorGeneralInformation(dateOfBirth, joinDate, identityNo, expiryDate, gender, doctorTitle, employmentType, identityType);
doctorRegistrationPage.fillDoctorContactInformation(mobileNumber, companyEmail);
doctorRegistrationPage.fillDoctorOtherInformation(doctorInformationEnglish, doctorInformationArabic);
doctorRegistrationPage.fillDoctorTiming(followUpDays, slotDurationMinutes);
doctorRegistrationPage.fillDoctorHospitalsAndClinics(hospital, clinics);
doctorRegistrationPage.fillDoctorDefaultProcedure(defaultProcedur, consultationProcedure);
boolean result = doctorRegistrationPage.verifyCreatedDoctor(doctorCode);
LOG.info("Return value of verifyCreatedDoctor method " + result);
softAssert.assertTrue(result, "TEST FAILED - CREATED DOCTOR NOT LISTING IN THE GRID");
softAssert.assertAll();
doctorRegistrationPage.logOutUser();
}
public void setDoctorRegistrationInformation() {
readPropertiesFile();
setNames();
setNumberValues();
setDate();
}
public void setNames() {
doctorFirstName = "AUT DN " + getRandomStringName(4);
doctorFamilyName = "AUT DFN " + getRandomStringName(4);
companyEmail = getRandomStringName(5) + "#aut.com";
doctorInformationEnglish = getRandomStringName(6);
}
public String getRandomStringName(int randomStringLength) {
return RandomStringUtils.randomAlphabetic(randomStringLength).toLowerCase();
}
public int generateRandomNumber(int low, int high) {
return (new Random()).nextInt(high - low) + low;
}
}
I have another class ( DoctorScheduleTest.java ) and needs to pass doctorCode , doctorFirstName , doctorFamilyName from (DoctorRegistrationTest.java ) to doctorSchedulePage.selectDoctorDropdown(doctor); method, instead of hardcoding the detail. Must pass the value like this (" doctorCode: doctorFirstName doctorFamilyName )
private String doctor =" 8938: AUT DN gvgl AUT DFN wnrn ";
#BeforeMethod(groups = {"BVT", "Regression"})
public void loadRmsPage()
{
loadRmsProfile();
softAssert = new SoftAssert();
doctorSchedulePage = new DoctorSchedulePage(webDriver);
}
#Epic("RMS")
#Feature("RMS - Create Doctor Schedule functionality")
#Story("AUT-835")
#Severity(SeverityLevel.BLOCKER)
#Test(description = "Positive : Doctor Schedule Creation", groups = {"BVT", "Regression"})
public void doctorScheduleCreationTestMethod()
{
setTemplateName();
createInitialSchedule();
setSchedule();
saveTemplate();
setTemplate();
setDateRange();
generateSchedule();
}
public void createInitialSchedule()
{
doctorSchedulePage.loadDoctorScheduleDashboard();
doctorSchedulePage.selectHospitalDropDown(hospital);
doctorSchedulePage.selectClinicDropDown(clinic);
doctorSchedulePage.selectDoctorDropdown(doctor);
doctorSchedulePage.fillTemplate(scheduleTemplateName);
}
public void setSchedule()
{
doctorSchedulePage.sundaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.mondaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.tuesdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.wednesdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.thursdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.fridaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
doctorSchedulePage.saturdaySchedule(startHourTime,startMinuteTime,startSchedule,endHourTime,endMinuteTime,endSchedule);
}
public void saveTemplate()
{
doctorSchedulePage.saveTemplate();
}
public void setTemplate()
{
doctorSchedulePage.selectTemplateDropdown(scheduleTemplateName);
}
public void setDateRange()
{
doctorSchedulePage.selectScheduleDate(scheduleStartDate,scheduleEndDate);
}
public void generateSchedule()
{
doctorSchedulePage.generateSchedule();
}
public int generateRandomNumber(int low, int high)
{
return (new Random()).nextInt(high - low) + low;
}
public void setTemplateName()
{
scheduleTemplateName = "Template " + getRandomStringName(3);
}
public String getRandomStringName(int randomStringLength)
{
return RandomStringUtils.randomAlphabetic(randomStringLength).toLowerCase();
}
}
DoctorSchedulePage.java ( selectDoctorDropdown method )
public void selectDoctorDropdown(String doctorcode)
{
selectValueFromDropDown(doctorDropdown, doctorcode);
}
BasePage.java (selectValueFromDropDown method )
protected void selectValueFromDropDown(WebElement element, String value) {
if (value != null && !value.isEmpty()) {
waitForElementToPresent(element);
Select dropdown = new Select(element);
LOG.info("Selected "+value);
dropdown.selectByVisibleText(value);
}
}
First of all, your question indicates, that you have an issue with passing a test data into tests. That should be addressed in the first place.
Since that is another topic (and a much bigger one) I would recommend a workaround, using a separate class, with a doctor's data.
public static class Doctor{
public static String FirstName;
public static String FamilyName;
Initialize the data in the setup and use is whenever you need.
As I said before, that is not the best solution, as testing data should be kept outside of the tests, but might be helpful for now.

jsoup to get div elements with classes

I am new to Jsoup parsing and I want to get the list of all the companies on this page: https://angel.co/companies?company_types[]=Startup
Now, a way to do this is actually to inspect the page with the div tags relevant to what I need.
However, when I call the method :
Document doc = Jsoup.connect("https://angel.co/companies?company_types[]=Startup").get();
System.out.println(doc.html());
Firstly I cannot even find those DIV tags in my consol html output, (the ones which are supposed to give a list of the companies)
Secondly, even if I did find it, how can I find a certain Div element with class name :
div class=" dc59 frw44 _a _jm"
Pardon the jargon, I have no idea how to go through this.
The data are not embedded in the page but they are retrieved using subsequent API calls :
a POST https://angel.co/company_filters/search_data to get an ids array & a token named hexdigest
a GET https://angel.co/companies/startups to retrieve company data using the output from the previous request
The above is repeated for each page (thus a new token & a list of ids are needed for each page). This process can be seen using Chrome dev console in Network tabs.
The first POST request gives JSON output but the second request (GET) gives HTML data in a property of a JSON object.
The following extracts the company filter :
private static CompanyFilter getCompanyFilter(final String filter, final int page) throws IOException {
String response = Jsoup.connect("https://angel.co/company_filters/search_data")
.header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
.header("X-Requested-With", "XMLHttpRequest")
.data("filter_data[company_types][]=", filter)
.data("sort", "signal")
.data("page", String.valueOf(page))
.userAgent("Mozilla")
.ignoreContentType(true)
.post().body().text();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
return gson.fromJson(response, CompanyFilter.class);
}
Then the following extracts companies :
private static List<Company> getCompanies(final CompanyFilter companyFilter) throws IOException {
List<Company> companies = new ArrayList<>();
URLConnection urlConn = new URL("https://angel.co/companies/startups?" + companyFilter.buildRequest()).openConnection();
urlConn.setRequestProperty("User-Agent", "Mozilla");
urlConn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
HtmlContainer htmlObj = new Gson().fromJson(reader, HtmlContainer.class);
Element doc = Jsoup.parse(htmlObj.getHtml());
Elements data = doc.select("div[data-_tn]");
if (data.size() > 0) {
for (int i = 2; i < data.size(); i++) {
companies.add(new Company(data.get(i).select("a").first().attr("title"),
data.get(i).select("a").first().attr("href"),
data.get(i).select("div.pitch").first().text()));
}
} else {
System.out.println("no data");
}
return companies;
}
The main function :
public static void main(String[] args) throws IOException {
int pageCount = 1;
List<Company> companies = new ArrayList<>();
for (int i = 0; i < 10; i++) {
System.out.println("get page n°" + pageCount);
CompanyFilter companyFilter = getCompanyFilter("Startup", pageCount);
pageCount++;
System.out.println("digest : " + companyFilter.getDigest());
System.out.println("count : " + companyFilter.getTotalCount());
System.out.println("array size : " + companyFilter.getIds().size());
System.out.println("page : " + companyFilter.getpage());
companies.addAll(getCompanies(companyFilter));
if (companies.size() == 0) {
break;
} else {
System.out.println("size : " + companies.size());
}
}
}
Company, CompanyFilter & HtmlContainer are model class :
class CompanyFilter {
#SerializedName("ids")
private List<Integer> mIds;
#SerializedName("hexdigest")
private String mDigest;
#SerializedName("total")
private String mTotalCount;
#SerializedName("page")
private int mPage;
#SerializedName("sort")
private String mSort;
#SerializedName("new")
private boolean mNew;
public List<Integer> getIds() {
return mIds;
}
public String getDigest() {
return mDigest;
}
public String getTotalCount() {
return mTotalCount;
}
public int getpage() {
return mPage;
}
private String buildRequest() {
String out = "total=" + mTotalCount + "&";
out += "sort=" + mSort + "&";
out += "page=" + mPage + "&";
out += "new=" + mNew + "&";
for (int i = 0; i < mIds.size(); i++) {
out += "ids[]=" + mIds.get(i) + "&";
}
out += "hexdigest=" + mDigest + "&";
return out;
}
}
private static class Company {
private String mLink;
private String mName;
private String mDescription;
public Company(String name, String link, String description) {
mLink = link;
mName = name;
mDescription = description;
}
public String getLink() {
return mLink;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
}
private static class HtmlContainer {
#SerializedName("html")
private String mHtml;
public String getHtml() {
return mHtml;
}
}
The full code is also available here

Why is my assertion that the element contains a certain String failing even though it is there?

the assert at the end of the main method is failing, even though that string is contained within the element, at least according to the console write line i perform before the assert.
can anyone help me figure out why that assert is failing? I'm at my wit's end. Literally pulling my hair out.
And sorry if it's a mess, I am new to Java.
enum Item {
DRILL(100.00, "a0Gf40000005CctEAE", "Drill"), ///
WRENCH(15.00, "a0Gf40000005CcuEAE", "Wrench"), ///
HAMMER(10.00, "a0Gf40000005CcvEAE", "Hammer"); ///
private final double _price;
private final String _itemID;
private final String _itemDisplayName;
Item(double price, String itemID, String itemDisplayName){
this._price = price;
this._itemID = itemID;
this._itemDisplayName = itemDisplayName;
}
double getItemPrice() {
return _price;
}
String getItemID() {
return _itemID;
}
String getItemName() {
return _itemDisplayName;
}
}
public class TestCaseOne {
static WebDriver driver;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
//System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Item testItem = Item.WRENCH;
driver.get("http://test.com/WebOrderScreen");
AddItem(testItem);
ChangeItemQuantity(testItem, 3);
driver.findElement(By.xpath("//span[text()='Payment Information']")).click();
WebElement itemLink = driver.findElement(By.id("order-summary")).findElement(By.xpath(String.format(".//a[(#href='/%s')]", testItem.getItemID())));
WebElement itemParentRow = itemLink.findElement(By.xpath("../../../.."));
String text = itemParentRow.getText();
System.out.println(text);
Assert.assertTrue(itemParentRow.toString().contains(testItem.getItemName()));
}
public static void AddItem(Item item) {
//first find the link to the item we want
WebElement itemLink = driver.findElement(By.xpath(String.format("//a[(#href='/%s')]", item.getItemID())));
WebElement itemParentRow = itemLink.findElement(By.xpath("../../../.."));
itemParentRow.findElement(By.tagName("i")).click(); //now that we found the parent row of the item we want, click the button to add it
driver.findElement(By.id("shopping-cart")).findElement(By.xpath(String.format(".//a[(#href='/%s')]", item.getItemID())));
System.out.println("Item ENUM found in shopping cart: " + item);
///for debugging
/*
System.out.println(item.getItemID());
System.out.println(item.getItemPrice());
System.out.println(itemParentRow.getText());
*/
}
public static void ChangeItemQuantity(Item item, Integer quantity) {
WebElement itemLink = driver.findElement(By.id("shopping-cart")).findElement(By.xpath(String.format(".//a[(#href='/%s')]", item.getItemID())));
WebElement itemParentRow = itemLink.findElement(By.xpath("../../../../.."));
//System.out.println("Old item count: " + itemParentRow.findElement((By.xpath(".//input[#inputmode='numeric']"))).getAttribute("value"));
itemParentRow.findElement((By.xpath(".//input[#inputmode='numeric']"))).clear();
itemParentRow.findElement((By.xpath(".//input[#inputmode='numeric']"))).sendKeys(quantity.toString());
//System.out.println("New item count: " + itemParentRow.findElement((By.xpath(".//input[#inputmode='numeric']"))).getAttribute("value"));
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='shopping-cart']//td[#class='nx-summary']")));
}
}
In the assertion you are calling toString() on WebElement, which returns something like:
[[[[[[ChromeDriver: chrome on LINUX (084b45f48be31410009e34b87903f54a)] -> id: order-summary]] -> xpath: .//a[(#href='/a0Gf40000005CcuEAE')]]] -> xpath: ../../../..]
Just like Andy indicated, you should use itemParentRow.getText().

How to add looping condition for selenium java code

I need to automate links in my website. I want to pass xpath values once in each iteration of loop. So that I can minimize my coding
public class Popup
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.example.com/info.php";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testPopup() throws Exception {
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[2]/i")).click();
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[3]/i")).click();
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[4]/i")).click();
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[5]/i")).click();
Can you try this?
for(int j=2; j<=5; j++) {
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a["+j+"]/i")).click();
}
Hi Sanchit Khera Try this one :
int i = 0;
//extract the link texts of each link element
for (WebElement e : linkElements)
{
linkTitles[i] = e.getText();
i++;
}
//Test each link
for (String t : linkTitles)
{
// Titles Click
driver.findElement(By.linkText(t)).click();

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.

Categories