Alert doesn't close using Selenium WebDriver with Google Chrome. - selenium-webdriver

I have the following Selenium script for opening alert on rediff.com:
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
Thread.sleep(5000);
Alert alert=driver.switchTo().alert();
alert.accept();
}
}
This very same script is working fine in Firefox and IE9, however using Google Chrome after opening the alert, rest of the code is not working. The main thing is that does not shows any exception, error or anything.
Please provide any solution as soon as possible.
Thanks a lot!
Note: If we need to change any setting of browser or any thing please let me know.
Selenium version:Selenium(2) Webdriver
OS:Windows 7
Browser:Chrome
Browser version:26.0.1410.64 m

I'm pretty sure your problem is a very common one, that's why i never advise using Thread.sleep(), since it does not guarantee the code will run only when the Alert shows up, also it may add up time to your tests even when the alert is shown.
The code below should wait only until some alert is display on the page, and i'd advise you using this one Firefox and IE9 aswell.
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
}
Mostly all that is done here, is changing Thread.sleep(), for a condition that actually will only move forward on the code as soon a alert() is present in the page. As soon as someone does, it wil switch to it and accept.
You can find the Javadoc for the whole ExpectedConditions class here.

Unfortunately AlertIsPresent doesn't exist in C# API
http://selenium.googlecode.com/git/docs/api/dotnet/index.html
You can use something like this:
private static bool TryToAcceptAlert(this IWebDriver driver)
{
try
{
var alert = driver.SwitchTo().Alert();
alert.Accept();
return true;
}
catch (Exception)
{
return false;
}
}
public static void AcceptAlert(this IWebDriver driver, int timeOutInSeconds = ElementTimeout)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutInSeconds)).Until(
delegate { return driver.TryToAcceptAlert(); }
);
}

Related

My XML file doesn't seem to be pushing the values to my code. Causing my tests to be skipped

I am setting up test cases for practice and trying to feed the parameters from an XML file for the website url, and the desired browser if available. The Switch logic, and webdriver commands look solid, but maybe i missed something that makes it skip them entirely. Should output that login was successful on both occasions.
In the past I've simply fed the data in as variables, this is my first try with xml handling the data injection.
public class NewTest {
WebDriver driver;
#Test(dataProvider="getData")
public void login(String username,String password)
{
//Code to Login to the application
driver.findElement(By.xpath("//*[#id=\'myNavbar\']/ul/li[4]/a")).click();
driver.findElement(By.id("usernameLogin")).sendKeys(username);
driver.findElement(By.id("passwordLogin")).sendKeys(password);
driver.findElement(By.id("login")).click();
try
{
//verifying the presence of webelement
````````````````````````````````````````````
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("topMenu2")));
System.out.println("login success");
}
catch(Exception e)
{
System.out.println("Login failure");
}
driver.findElement(By.id("topMenu2")).click();
}
#DataProvider
public Object[][]getData() {
Object[][]data=new Object[2][2];
data[0][0]="pgGru";
data[0][1]="freezeray";
data[1][0]="pgAlmacho";
data[1][1]="freezeray";
return data;
}
#BeforeSuite
#Parameters({ "browsername", "url" })
public void setup(#Optional("Firefox")String browsername,String url) {
switch (browsername) {
case "IE":
WebDriver driver1;
driver1 = new InternetExplorerDriver();
System.setProperty("webdriver.IEDriverServer.driver", "D:\\Jarrrs\\Drivers\\IEDriverServer_win32");
driver1.get(url);
break;
case "Firefox":
WebDriver driver2;
driver2 = new FirefoxDriver();
System.setProperty("webdriver.geckodriver.driver","D:\\Jarrrs\\Drivers\\gecfkoDriver_win32");
driver2.get(url);
break;
case "chrome":
WebDriver driver3;
driver3 = new ChromeDriver();
System.setProperty("webdriver.chrome.driver, ","D:\\Jarrrs\\Drivers\\chromedriver_win32\\chromedriver.exe");
driver3.get(url);
break;
}
}
#AfterSuite
public void tearDown() {
driver.quit();
}
}
Right now the output is it is skipping the test cases for login and password
Expecting two passed or failed tests. Either one would be nice.
Newbie here. What do you mean by test is skipping? Are the actions within login() not being executed? I would put sys.out statements withing login() to check if the code is getting executed. How about adding a pause after page load? How about adding hardcoded value to username and password field to check if it is working fine?
Some times certain fields cannot be set by using Selenium's sendkeys. Need to use JavascriptExecutor to set the field values

org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: Cannot click on element

Getting below exception error while running the code in IE browser. However same works fine Firefox and Chrome browser. Can someone help?
I am trying to run the below code in IE browser and trying to click on link "create button" on page https://en.wikipedia.org/wiki/Selenium_%28software%29. But link never gets clicked , same code works fine in Firefox.
can you please advise if I need to make any changes
public class ClickIE {
public static void main(String[] args) throws InterruptedException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("requireWindowFocus", true);
System.setProperty("webdriver.ie.driver", "C:\\Users\\Nitin\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(caps);
driver.get("https://en.wikipedia.org/wiki/Selenium_%28software%29");]
Thread.sleep(5000);
driver.manage().window().maximize();
driver.findElement(By.xpath("/html/body/div[4]/div[1]/div[1]/ul/li[4]/a")).click();
String url = driver.getCurrentUrl();
if(url.contains("wikipedia")) {
System.out.println(url+" its a internal link - Passed");
}
else {
System.out.println(url+" its a external link - Failed");
}

IEDriver implementation fails the test

I am using Webdriver(without IEDriver implementation) 2.23 API on windows7 machine with JDK7 and JRE7. The test scripts are working fine as expected but when i introduced IEDriver the script fails in a page with cannot click on element error message as that corresponding element is not visible. i have double checked with my application for the locator. The same can be clicked with out IEDriver implementation. I have tried by simulating all the click types including context click by Action class. No use. All click types returns the same result. Any help ?
Finally, i was manage to click the above said Element with the help of following code.
WebElement we = driver.findElement(By.name("Complete"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", we); // common for all we
The real source is here. This may helpful for someone.
As you say that the element is actually visible and the error's log says it is not, I think that the problem might be due to Internet Explorer's slowness. You could use this method for a quick test:
boolean isElementDisplayed(final WebDriver driver, final WebElement element, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
return element.isDisplayed();
}
};
Wait w = new WebDriverWait(driver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
//if you get here, it's because the element is not displayed after timeoutInSeconds
return false;
}
return true;
}
Use it like this:
WebElement we = driver.findElement(By.name("Complete"));
if (isElementDisplayed(driver, we, 30)) {
we.click();
}
This will make the driver wait (30 sec max.) till the element we becomes visible and then the driver clicks on it.
If it works, then my supposition is right and you could change the method for:
void clickOn(final WebDriver driver, final WebElement element, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
element.click();
return true;
}
};
Wait w = new WebDriverWait(driver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
//probably some kind of exception thrown here
}
return;
}
and use it instead of we.click(), like:
WebElement we = driver.findElement(By.name("Complete"));
clickOn(driver, we, 30);
The code above is an approximation to let you check your issue in a quick and clear way and, if you end up using it, you should adapt it to your structure of code. This kind of utility code should never appear in your tests. Your test code should be clean and the same for all the environments (browsers, version, SOs, etc.). Keep the workarounds separately, e.g. some kind of util package.
Also, the method's signature is 'overweight'. Restructuring your util code, you should be able to write in your tests just this: clickOn(element).
Hope it helps ;)
UPDATE Actually, with these components I had never run into a similar problem:
selenium-server-standalone version 2.32.0
IEDriverServer_x64_2.30.1.exe

How can I run Fluentlenium Code inside Selenium Webdriver Firefox Driver?

I am having issues trying to get my Fluentlenium code to run inside the WebDriver Firefox Driver. I need Fluentlenium to execute inside the WebDriver Firefox Driver instead of opening it's own browser. I think I need to override this but I am not exactly sure how to do this. Any help would greatly appreciated. Thanks! Here is what I have for code:
WebDriver driver = new FirefoxDriver();
#Test
public void create_a_picklist()
{
// Go to Page
goTo("http://www.google.com");
}
What happens is that it opens two browsers. One is from the Firefox Driver and the other must be the default browser from the goTo from Fluentlenium. I need it to run this code inside the Firefox Driver window and not open it's own window from Fluentlenium.
By default, it launchs a Firefox browser so that's sufficient :
public class Test extends FluentTest {
#Test
public void go_to_google()
{
goTo("http://www.google.com");
}
}
And nothing more :)
Ok. Looks like I figured it out. Here is what I did to override the browser:
public class Test extends FluentTest {
// Defines the Driver
public WebDriver driver = new FirefoxDriver();
// Overrides the default driver
#Override
public WebDriver getDefaultDriver() {
return driver;
}
#Test
public void go_to_google()
{
goTo("http://www.google.com");
}
}

Different Screen Shot Resolution in Different Browsers

I am facing a problem related to my Project of GUI comparison...
It takes Screen Shots of given URL in different Browsers, but these Screen Shots are having different Resolution for different Browser.
So, my problem is that now what to do for getting the Same Resolution of all the screen shots in different Browsers.???
If any solution is there then kindly tell me.
Detail:
Resolutions With:
Mozilla Firefox:- 1345*627
Google Chrome:- 1345*659
Internet Explorer:- 1345*679
Tools used:
Selenium Web Driver.
Java
Try maximising the driver window
Example with Junit & webdriver:
public class Untitled {
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.google.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
#Test
public void testUntitled() throws Exception {
driver.get(baseUrl);
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}`

Resources