Script is getting pass with out clicking the element - java

The Below code I was writing , where the element will get store in list , and click randomly using the java random method and after clicking it should print the success message
ISSUE : the Code is getting pass and printing the success message without clicking any web-element
List<WebElement> ev_Collection = driver.findElements(By.xpath("//div[#class='collection-card']");
Random random = new Random();
int index = random.nextInt(ev_Collection.size());
System.out.println("the bound is "+ index) ;
ev_Collection.get(index).click();
System.out.println("Success ");
Do I need to change the above code please let me know

It looks to me like right now there's no conditional for testing if anything was clicked. Rather the code is running sequentially and the last line to be run is a print statement.
Try using a ClickHandler and putting the print statement inside that.

Related

Getting the error " bound must be positive" while trying to select a random radio button

IMAGE OF LIST OPTIONSI am trying to select a random radio button out of multiple radio buttons through the below-mentioned code:
addapp.ClickSelectUnit();
List < WebElement > options = driver.findElements(By.xpath("//input[#type='radio' and #name='application[unit_space_id]']"));
Random ran = new Random();
int index = ran.nextInt(options.size());
options.get(index).click();
But getting the error:
2019-10-31 20:24:50 ERROR TestUtilsRV:141 - bound must be positive
2019-10-31 20:24:52 INFO TestUtilsRV:134 - Quit Driver
When I run the code in Debug Perspective by putting a breakpoint at the first line it selects the random checkbox but when I run it in maven through command prompt I keep getting this error. Please help me get through this.
I made following changes to the code and it worked perfectly for me:
List options=wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(xpath)));
#Andy: Yes, options was empty and by using the wait for visibility for the list elements the issue got resolved.

if (!string.equals.string) seems to be running all the time not only if it doesn't equal

When running my code, I have come across ! before a statement to have negative or opposite of the statement. In this case if --- this string does not equal this string.
I've tried changing the second value in the string and it corrects it every time but I watch my tests and the values are correct and it still runs. I'm stuck wondering why because I need this as a check before moving on and Selenium 5-10% of the time types into the field too fast. This is why I implemented this check.
driver.findElement(By.id("inputcardNumberField")).sendKeys("41111111111111111");
WebElement visa = driver.findElement(By.id("inputcardNumberField"));
String visa2 = visa.getText();
Thread.sleep(2000);
if (!visa2.equals("4111111111111111")) {
driver.findElement(By.id("inputcardNumberField")).clear();
driver.findElement(By.id("inputcardNumberField")).sendKeys("4111111111111111");
}
That if Selenium fills the inputcardNumberField too fast and the whole card # is not present.. it should clear and re-enter it.
If the correct card# is present it should not have to re-enter it. It re-enters it every time right now
Looks like I was missing the get attribute value-- It should be like this:
driver.findElement(By.id("inputcardNumberField")).sendKeys("4111111111111111");
WebElement visa = driver.findElement(By.id("inputcardNumberField"));
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
String value = driver.findElement(By.id("inputcardNumberField")).getAttribute("value");
Thread.sleep(2000);
if (!visa2.equals("4111111111111111")) {
driver.findElement(By.id("inputcardNumberField")).clear();
driver.findElement(By.id("inputcardNumberField")).sendKeys("4111111111111111");
}

define a Custom Property as a Data Object

Found the issue on my payment Input control. There was a small computed Text field that was failing but not throwing an error. Just stopped the whole process. In any case removed the computedText and it now works. The compositeData formula that returns pItem to the custom control still fires way to often but I can't figure out how to stop that. It is all memory resident so it is probably not a major performance hit, but still.....
This question is a follow up to my previous question and I will try to refine the issue
defining an object property in a compositeData on a custom control
Here is a picture of what I am trying to do:
The repeat control is bound to an arrayList generated by the Java method Payments.getAllItems(LinkKey) and that works correctly. The button in the repeat is fairly simple it just setts the viewScope.vsShowPayment = true and vsRIndex to the repeat Index value so I know which element in the ArrayList we are working with. It then does a refresh of the panelPaymentContainer which hides the repeat and renders the custom control ccTestPayment.
ccTestPayment has a custom property called pItem of the type java.lang.Object with this code:
<xc:ccTestPaymentInput rendered="#{javascript:(viewScope.vsShowPayment)}">
<xc:this.pItem><![CDATA[#{javascript:try{
var debug:Boolean = true;
if (debug) print("Open existing row = " + viewScope.vsRIndex)
rIndex = parseInt(viewScope.vsRIndex.toString());
if (debug) print("rIndex = " + rIndex);
pItem = Payments.getItem(rIndex);
return pItem;
}catch(e){
print("Failure in Custom Prop of add item " + e.toString());
return null;
}}]]></xc:this.pItem>
</xc:ccTestPaymentInput>
the method in the class Payments Payments.getItem(rIndex) then returns the PaymentItem Object from the ArrayList of PaymentItems and displays them in custom control. the fields in the custom control are bound to compositeData.pItem.getPaymentDate etc and to this point everything is cool.
I can edit any of the fields on the custom control and that all works fine. However, when I press the "Save" button none of the code in it gets executed.
try{
print("Start Payment save");
var debug:Boolean = true;
var pos:Integer = parseInt(viewScope.vsRIndex.toString());
if (debug) print("Working with pos = " + pos + " Call saveThisItem");
if (Payments.saveThisItem(compositeData.pItem , pos)){
if (debug) print("save Payments Worked ");
}else{
if (debug) print("save Payments FAILED ");
}
}catch(e){
print("payment save Error " + e.tostring);
}finally{
viewScope.vsExpPayDate = null;
viewScope.vsShowPayment = false;
viewScope.remove("vsRIndex");
viewScope.remove("vsGotItem")
}
None of the print statements get fired. I suspect it has something to do how pItem gets defined. the code behind the custom property gets fired over and over again and I'm wondering if that is getting in the way.
The reason that the save was not working was that there was a computed Text field on the control that generated an error. The problem was that there was no error message reported on the client nor the console. After a lot of head scratching I noticed the text filed was no longer displaying the value it was supposed to. Deleted the field and the save and everything else started to work.
On the issue of the number of times the processes are called I think I have resolved many of them. I'm moving the control ccTestPaymentInput.xsp inside the repeat. It will now have direct access to the 'current' PaymentItem Object so I can access teh repeat var=pItem which is teh PaymentItem object I want to work with. Clean and far simpler than what I was doing. The only refreshes necessary are the ones related to the rpeat control and there is not much that I can do about that.

How do I click on an image button in WebDriver using Java?

The button type is image, and the relevant code in HTML code attached. I have entered all the data and clicked on Apply Now button, it is not at all saving. But when I try to create it manually, it is saved in less than 15 seconds.
Please find the attached screen shot.
The relevant code for the same:
//Navigating to Quick Application
driver.get(QAurl);
Thread.sleep(15000);
driver.findElement(By.id("DdlSalesPerson")).sendKeys("Swamy m Kumara");
driver.findElement(By.id("TxtFName")).sendKeys("Kumar");
driver.findElement(By.id("TxtLName")).sendKeys("Swamy");
driver.findElement(By.id("TxtAddress")).sendKeys("434, Main Road, Somajiguda");
driver.findElement(By.id("TxtZip")).sendKeys("79081");
driver.findElement(By.id("TxtSSN1")).sendKeys("881");
Thread.sleep(15000);
driver.findElement(By.id("TxtSSN2")).sendKeys("72");
driver.findElement(By.id("TxtSSN3")).sendKeys("4365");
Thread.sleep(5000);
driver.findElement(By.id("TxtDayPhone1")).sendKeys("963");
driver.findElement(By.id("TxtDayPhone2")).sendKeys("210");
driver.findElement(By.id("TxtDayPhone3")).sendKeys("5478");
Thread.sleep(5000);
driver.findElement(By.id("ChkIAgree")).click();
driver.findElement(By.id("TxtSignature")).sendKeys("Kumar Swamy");
Thread.sleep(5000);
System.out.println("Entered all the required fields");
//Reading the value in the image.
WebElement element = driver.findElement(By.id(OR.getProperty("FP_SImg_ID")));
String src = ((JavascriptExecutor)driver).executeScript("return arguments[0].attributes['src'].value;", element).toString();
img =src.split("=");
System.out.println("Value retrieved from the Image source: "+img[1]);
driver.findElement(By.id(OR.getProperty("FP_TxtSImg_ID"))).sendKeys(img[1]);
Thread.sleep(5000);
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
driver.findElement(By.name("BtnSubmit")).click();
Thread.sleep(35000);
System.out.println("Successfully Applied from the QuickApp");
HTML code for the Apply now button:
<input id="BtnSubmit" type="image" style="height:33px;width:121px;border-width:0px;"
onclick="javascript:return validateControls();" src="../Common/Images/HybridQA
/apply_now.png" title="Submit Here" tabindex="45" name="BtnSubmit">
Any help will be appreciated.
You have 1 minute 25 seconds of Thread.sleep() in your code...
Remove all the thread.sleep(), if you are waiting for elements to appear do it properly, use an explicit wait:
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
To take an example from the page linked above:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Have a look at the ExpectedConditions class to see the available conditions built into selenium, if they don't meet your needs it's trivial to write your own expected conditions.
-------------------Edit-------------------
For the record this answer is for the original question that was asked which is quoted below (you can have a look at the edit history of the original question to verify this as well).
Taking long time to save after clicking on Apply Now button using Webdriver in Java
Taking long time to save after clicking on Apply Now button using
Webdriver in Java. I have entered all the data and clicked on Apply
now button, it is not at all saving. But when i try to create it
manually, it is saved in less than 15 seconds. Please find the
attached screen shot.
There could be 2 reasons for this problem.
One is from the HTML code of 'Apply Now' button, I could see that it shows as "input
id='BtnSubmit'", but in your script its written as
'driver.findElement(By.name("BtnSubmit")).click();'.
Shouldn't it be "driver.findElement(By.id("BtnSubmit")).click()"?; 'name' must be
replaced with 'id'.
At the end of the script you click 'BtnSubmit', the session might expire immediately after
you click that button. This problem usually occurs when you use an older and new version
of selenium standalone jar file. See to that you use only the latest version and not in
addition to an old version.
Use this,
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
after this,
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
and comment,
driver.findElement(By.name("BtnSubmit")).click();
So your code looks like,
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
//driver.findElement(By.name("BtnSubmit")).click();
Sometimes it's difficult to handle image buttons because these buttons are activated when all required fields are entered. Make sure you filled all mandatory fields and press enter after entering last field in the form. First try to do it manually. Instead of clicking on button press enter at last input field and use same stratefy with automation.
Update:
Use your own code and replace Thread.sleep() with below method.
Call it like,
waitForElementToBePresent(By.id("DdlSalesPerson"), 15000);
It waits for next element whichever you pass as argument. It returns true if found or false if not. If element found within the given time it will return true immediately instead of waiting for given time.
public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
{
WebDriver driver = getDriver();
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
List<WebElement> elements = driver.findElements(by);
if (elements != null && elements.size() > 0)
return true;
Thread.sleep(250);
}
return false;
}

sendKeys.RETURN not working in FirefoxDriver

if I execute the following code in FireFoxDriver:
WebElement element = driver.findElements(By.id("some_id")); // element being a textbox
element.sendKeys("apple");
element.sendKeys(Keys.RETURN);
The sendKeys(Keys.RETURN) is not performing its desired function.
Actually what I am trying to do is Input a text in a dynamic text search box (like one in facebook search) and press enter. The input is working fine but not the enter key.
sendKeys("apple") works, even sendKeys(Keys.BACK_SPACE) works, but not Keys.RETURN.
Does anyone have ideas? Thanks guys!
Not exactly sure why this happens, but there are a couple alternate ways of doing this that may help:
If elements are in a form, and there is no javascript that runs on submit or something you can use .submit() on any form input element, such as inputs and textareas:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple");
element.submit()
You can send the newline character with your input:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple\n");
Provide send_keys a list:
WebElement element = driver.findElements(By.id("some_id"));
element.sendKeys("apple", Keys.ENTER);
Got the solution to the above problem. U just need to add, a delay.
This happens because the Java Class runs too fast, so if u have sent a call, and pressed enter/ tab, before the element arrives, the enter is pressed, that is why this doesn't work. Just add Thread.delay(1000); before your Keys.RETURN command. That will do.
Worked for me.
I tried sending \n and fiddled with various commands until I found someone explaining that "keyPress (target) 13" will send the return key.
So first I use type to enter the string I want ...
*
*<tr>
<td>type</td>
<td>id=status</td>
<td>This is my test string</td>
</tr>*
*
... and then send the Enter key to the same text input box
*
*<tr>
<td>keyPress</td>
<td>id=status</td>
<td>13</td>
</tr>*
*

Categories