WebDriver browser selection - selenium-webdriver

I want to create method that start using 1 of the browsers (IE, Chrome, FireFox) and if one of them not exist then move to the other browser?
For exemple start with FF and if not exist then move to Chrome and if not exist then move to IE and if its also don't exist then assert.

Write one utility method that instantiate the driver object in try catch block and returns the first available driver(FF/IE/Chrome) object; if first one doesn't exists code will try to instantiate 2nd browser and so on...
Here is the sample code structure:
private WebDriver getDriver(){
WebDriver driver = null;
try{
driver = new FirefoxDriver();
return driver;
} catch (Exception e){}
try{
driver = new InternetExplorerDriver();
return driver;
} catch (Exception e){}
try{
driver = new ChromeDriver();
return driver;
} catch (Exception e){}
return driver;
}
//Then call the getDriver method and assert not equal to null.
WebDriver driver = getDriver();
Assert.assertNotNull(driver);
//Continue with your tests...

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

Delete Cache and Cookies

I have different roles of login. Menu will be different for each user login.
I do login for user1 and Logout and then proceeding further user.
On each login, I am using deleteAllCookies() before launching the url. But I am facing that the session is retained and directly logs in the last logged in user.
The following combination I have tried. it did not work for.
public static WebDriver driver;
1. deleteAllCookies()
2. DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, false);
driver = new InternetExplorerDriver(capabilities)
3. DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
driver = new InternetExplorerDriver(capabilities)
How to avoid this?
I have tried below code and it's working by deleteAllCookies().
WebDriver driver = null;
driver = new FirefoxDriver();
driver.get("http://stackoverflow.com/");
driver.findElement(By.xpath("html/body/div[3]/div/div[3]/div[1]/span/a[2]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='email']")).sendKeys(<Enter your email>);
driver.findElement(By.xpath("//*[#id='password']")).sendKeys(<Enter your password>);
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='submit-button']")).click();
Thread.sleep(1000);
System.out.println("Get");
System.out.println(driver.manage().getCookies());
driver.manage().deleteAllCookies();
System.out.println("Delete");
System.out.println(driver.manage().getCookies());
driver.get("http://stackoverflow.com/");
This works fine for me.
try {
Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
Thread.sleep(3000);
} catch (IOException e) {
e.printStackTrace();
}

Appium : NullPointerException coming

I am trying to run the below code to automate my mobile application and every thing seems OK but I am getting NullPointerException on following line:
driver.findElement(By.id("com.app.aftertax.aftertax:id/Text7"));
Here is my code:
public class Login {
public static AndroidDriver driver;
#BeforeTest
public void setUp() throws Exception {
File classpathRoot = new File(System.getProperty("user.dir"));
File app = new File("/Users/hanan/Downloads/app-at.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "Android Emulator");
capabilities.setCapability("platformName","Android");
capabilities.setCapability("platformVersion","4.4");
capabilities.setCapability("app-package", "com.mobikwik_new");
capabilities.setCapability("app-activity", ".MobikwikMain");
capabilities.setCapability("app-wait-activity",
".MobikwikMain");
capabilities.setCapability("appiumVersion", "1.3.7");
//capabilities.setCapability("name", methodName.getName());
capabilities.setCapability("app", app.getAbsolutePath());
new AndroidDriver( new URL("http://localhost:4723/wd/hub"),
capabilities);
}
#Test
public void apiDemo() throws InterruptedException {
Thread.sleep(10000);
WebElement login = driver.findElement(By.id("com.app.aftertax.aftertax:id/Text7"));
login.click();
}
}
If your code line is the first in the stack trace (you should add the full stacktrace to such questions), then it's the driver variable which is not initialized (==null)
It seems that you are not assigning Appium object in below code:
new AndroidDriver( new URL("http://localhost:4723/wd/hub"),
capabilities);
You should create reference variable of AppiumDriver or AndroidDriver at class level. then assign created object in reference variable like below:
driver = new AndroidDriver( new URL("http://localhost:4723/wd/hub"),
capabilities);

Null pointer exception due to driver instance is null in onTestFailureMethod

Need help on - I am getting null pointer exception in onTestFailure method. If any of my #Test method fails control goes to onTestFailure but driver is null in that method. my code is like -
import statements...
#Listeners(ScreenShot.class)
public class ScreenShot implements ITestListener{
WebDriver driver;
#BeforeClass
public void launch(){
System.setProperty("webdriver.ie.driver", "D:\\Jars\\Drivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("url");
}
#Test
public void test1(){
//driver.findElement(By.id("Email")).sendKeys("E#E.COM");
System.out.println("Method1 begins");
//some code here - exception occurs here
System.out.println("Method ended");
}
public void onTestFailure(ITestResult result){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Getting exception here as driver is null
try {
FileUtils.copyFile(scrFile, new File("C:\\snaps\\"+result.getMethod().getMethodName()+".png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i am running this class by right click->run as testng.
The reason you are getting a NullPointerException is because Testng creates a new instance of each listener. So that new instance has driver not initialized.
In your case, the object of Screenshot class running the #Test method and the instance of the Screenshot class as a listener being invoked by TestNG is different.
There are couple of ways to solve this.
Move the code from onTestFailure to #AfterMethod with the ITestResult as the method argument. Work on the result data to take screenshot.
#AfterMethod
public void afterMet(ITestResult res){
if(res.isSuccess())
Make the driver as a global static. - if you plan to run only sequential tests
Consider threadlocal if you plan to run parallely.

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

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(); }
);
}

Resources