Selenium Webdriver and TestNG - java

I'm running a code on webdriver with TESTNG... the first test works perfectly fine but after when I try executing test2 ... the driver.findelement gets underlined in red and doesn't execute at all. Previous driver.findelement was brown but after test2 is blue, any reason to why its not working?
#Test(priority=1)
public void launchSandBoxTestingTestNG() throws InterruptedException{
// Import FireFox Driver
WebDriver driver = new FirefoxDriver();
// Open up Sandbox Page
driver.get("****");
// Enter Usename and Password
// User
driver.findElement(By.id("userId")).sendKeys("****");
Thread.sleep(3000);
// Password
driver.findElement(By.id("password")).sendKeys("****");
Thread.sleep(3000);
// Click Login Button
driver.findElement(By.id("loginButton")).click();
}
#Test(priority=2)
public void test2(){
driver.findElement(By.xpath("****")).click();
// When I try running this code above it underlines the find element in red
// When I run it on web driver the test2 syntax doesnt work
//It gives me an option of casting an argument but not sure what that means
}
}

The question is not very clear may be this might be the problem.
You are creating an WebDriver object inside a function.
Make WebDriver object global.
Example
public class test {
WebDriver driver = new FirefoxDriver();
public void test1(){
//test logic
}
public void test2(){
// test logic
}
}

I would also put "#Test(priority=1)" inside the "public void launchSandBoxTestingTestNg" and declare the webdriver inside the "launchSandBoxTestingTestNG" but outside the test methods
public void launchSandBoxTestingTestNG() throws InterruptedException{
// Import FireFox Driver
WebDriver driver = new FirefoxDriver();
#Test(priority=1)
public void test1(){
// Open up Sandbox Page
driver.get("****");
// Enter Usename and Password
// User
driver.findElement(By.id("userId")).sendKeys("****");
Thread.sleep(3000);
// Password
driver.findElement(By.id("password")).sendKeys("****");
Thread.sleep(3000);
// Click Login Button
driver.findElement(By.id("loginButton")).click();
}
#Test(priority=2)
public void test2(){
driver.findElement(By.xpath("****")).click();
// When I try running this code above it underlines the find element in red
// When I run it on web driver the test2 syntax doesnt work
//It gives me an option of casting an argument but not sure what that means
}
}

Related

Java Selenium WebDriver Firefox how can i get boolean values from getStatus()?

im trying to make test in Eclipse, using Selenium and Firefox webdriver. I wrote next class:
public class Selenium {
FirefoxDriver driver;
#BeforeTest
public void setup(){
driver = new FirefoxDriver();
}
#Test
public void go_to(String url){
driver.get(url);
}
Now in my main class im trying do that:
String url = JOptionPane.showInputDialog("Please input where do you want to go");
selenium.setup();
report.start_report();
selenium.go_to(url);
But also, i want to write
if(selenium.driver.getStatus)
Is there any command, to take boolean value, from my driver.get(url)? For example, if successful go to web page, then true, and if error, then false?

Selenium Eclipse Test Suite tests fail in the suite, but are successful when run individually

I have the following test suite to run an automation script to login to gmail then another script to click the Compose button:
TestSuite.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Web Admin Tests" parallel="false">
<test name="BOS - Account Class">
<classes>
<class name="secondtestngpackage.GmailComposeEmail" />
<class name="secondtestngpackage.GmailLogin" />
</classes>
</test>
</suite>
When I run this test suite, the first test does not get passed the login screen in gmail, but the second test does, even though they reference the same functions. Is there a reason why this would happen? One test is able to enter the user id and password, since it is the second/last test, but when the first test is run, it is like the second test interferes with it, since its browser is now in focus.
GmailLogin.java:
#BeforeTest
public void launchBrowser() {
ReuseFunctions.OpenApp("Chrome", "https://gmail.com");
}
//Test 1: Log into Gmail
#Test(priority=1)
public void LoginToGmailAccount() {
**GmailComposeEmail.java**
#BeforeTest
public void launchBrowser() {
ReuseFunctions.OpenApp("Chrome", "https://gmail.com");
}
#Test(priority=2)
public void LoginToGmailAccount() {
Reusable Functions File:
ReuseFunctions.func_EnterCredentials("username", "password");
public class ReuseFunctions {
public static WebDriver driver;
/*Function 1: Select Browser and Open Application Function
*/
public static Object OpenApp (String Browser, String URL) {
//Receive Browser Name Function
Func_LaunchBrowser(Browser);
//Receive Website and Open Function
func_OpenURL(URL);
return driver;
}
//Select Browser
public static WebDriver Func_LaunchBrowser(String Browser) {
String driverPath = "C:/EclipseJavaDev/";
if(Browser=="Chrome"){
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
driver = new ChromeDriver();
}else if(Browser=="FF"){
driver= new FirefoxDriver();
}else if(Browser=="IE"){
System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
driver= new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
return driver;
}
//Open URL
public static void func_OpenURL(String URL){
driver.get(URL);
driver.manage().window().maximize();
}
The problem lies with where your WebDriver instance is instantiated. Think of each instance of WebDriver as a unique browser session. So the safest way to ensure each test gets its own driver instance (browser session), is to initialize it at the Test class, not the common helper class.
GmailLogin:
// Initialize Webdriver and then asks your common function to return it
private WebDriver driver;
#BeforeTest
public void launchBrowser() {
driver = ReuseFunctions.OpenApp("Chrome", "https://gmail.com");
}
#Test(priority=1)
public void LoginToGmailAccount() {
// pass driver as a method argument to other methods
}
//Don't forget to close the browser
#AfterTest
public void quitBrowser() {
driver.quit();
}
Refactor your other Test class the same away as above. (Or reconsider if you really need another class. You could just add another method into the same class and use priority and/or dependsOnMethods attributes to control the execution order. But that is a different topic and out of the scope of this question :) ).
ReuseFunctions:
// Remove the global Webdriver instantiation
//Change return type from Object to WebDriver
public static WebDriver OpenApp (String Browser, String URL) {
WebDriver driver = Func_LaunchBrowser(Browser);
func_OpenURL(URL, driver); //pass in the driver as arg
return driver;
}
//Refactor openUrl method to use the driver from arg
public static void func_OpenURL(String URL, WebDriver driver){...}
This should work. Let me know how it goes.

Multiple browser windows opening automatically in cucumber

I don't know why I am getting 2 firefox browsers opened for the follwoing example. Can some one please tell me what is wrong in below code. I am new to cucumber and I am trying to develop cucumber poc with page object model.
Feature file:
Scenario: Smoke test for application
Given I am on home page
Step Defination file:
public class HomePageSteps {
CustomerDetails customerDetails;
HomePage homePage=new HomePage();
public HomePageSteps(CustomerDetails customerDetails){
this.customerDetails=customerDetails;
}
#Before
public void environmentSteup(){
homePage.envSetup();
}
#Given("^I am on home page$")
public void i_am_on_home_page() throws Throwable {
homePage.openURL();
}
}
Actual implementation of Step definition file:(HomePage.java)
public class HomePage extends BasePage{
public void openURL() {
driver.get("https://applicationURL.aspx");
System.out.println("I am on home page executed");
}
public void envSetup() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
}
}
BasePage.java
public abstract class BasePage {
protected WebDriver driver=new FirefoxDriver();
}
CustomerDetails.java
public class CustomerDetails {
private String mdn=null;
private String Fname=null;
private String Lname=null;
public String getMdn() {
return mdn;
}
public void setMdn(String mdn) {
this.mdn = mdn;
}
}
2 firefox browsers are opened:
First it opens a blank browser. Later it opens another browser and in this browser it opens the application URL.
You have two calls to open browser windows...
Once in the sub-class in envSetup() - driver=new FirefoxDriver();
And in the super class driver variable declaration with initialization - protected WebDriver driver=new FirefoxDriver();
You have to remove one of them, no need for the super class one... This is the one giving you the blank window
Refer to this page. Your maximize() call in envSetup() might be doing more than you think
In selenium webdriver what is manage() [driver.manage()]
edit:
You also do not need to instantiate a new FirefoxDriver() outside of BasePage as you have already instantiated a driver field with that object. Anything extending BasePage will have access to that driver field. It is not a problem that you're doing this, it is just extraneous code that doesn't need to be there

How to Write a Function for WebElement Click in Selenium Webdriver

I am Having a Lot of WebElements
For Example I Declared a WebElement a
#FindBy(id="BtnLogin")
private WebElement btnLogin;
In the Same Manner I created "N" number of WebElements
Every time I Cant use "driver.findElement()" function So I wrote a function
public static void WebElementClick(WebElement we)
{
we.click();
}
When Ever the Control is Going to The Line we.click() in the WebElementclick Function it is Showing NullPointerException as a Result My Purpose is Failing
I am Not Getting What to Do,Some One Please Help Me on this :)
Your WebElementClick should receive the selector and it should: find element -> click, you can get an example from the above link.
In your case you it seems that you are not using wait and the WebElementClick it tries to click on the string.
Using find will return an object that will make click available.
The method should contain something like: driver.findElement(By.xpath("your_selector"));
Ant then use click on what this method returns.You can use also css if you want to.
public class testJava{
#Test
public void testMethod() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
pageClass pageClass = PageFactory.initElements(driver, pageClass.class);
driver.get("http://www.facebook.com");
Thread.sleep(5000);
pageClass.clickLoginBtn();
}}
public class pageClass {
#FindBy(id = "loginbutton")
private WebElement loginBtn;
WebDriver driver;
public pageClass(WebDriver driver) {
this.driver = driver;
}
public void clickLoginBtn()
{
click(loginBtn);
}
public void click(WebElement we)
{
we.click();
}}
Its best practice to use the page class & test class..Try this it will help you i guess.
You are suppose to use driver to find & click the element.
I think that driver may try to click element before it's presented. Good practice before clicking WebElement is to wait for WebElement being clickable. I would try:
public static void WebElementClick(WebElement we)
{
wait.forElementClickable(we);
we.click();
}

creating user defined function for selenium webdriver

I want to create some user defined functions for my webdriver automation code. I tried it, but resulted in failure.
the following is my code
public class snapdeal {
WebDriver driver= new FirefoxDriver();
#Test
public void test() {
// I want open browser in function 1
driver.get("http://amazon.in");
driver.manage().window().maximize();
// Function 2 for searching
driver.findElement(By.xpath("//li[#id='nav_cat_2'")).click();
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Shoes");
driver.findElement(By.xpath("//input[#class='nav-submit-input']")).click();
driver.findElement(By.xpath("//h2[#class='a-size-medium s-inline s-access-title a-text-normal' and contains(text(), \"Fbt Men's 8876 Casual Shoes\")]")).click();
}
}
How ca i write two functions inside the class?
You were probably trying to nest methods inside test() . It is not possible.
You can use this code below which calls the respective methods in the test(). It works as expected:
public class snapdeal {
static WebDriver driver= new FirefoxDriver();
#Test
public void test() {
//Method1 for Opening Browser.
openBrowser();
// Method2 for searching
searchElement();
}
public static void openBrowser(){
driver.get("http://amazon.in");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
public static void searchElement(){
driver.findElement(By.xpath("//li[#id='nav_cat_2']")).click();
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Shoes");
driver.findElement(By.xpath("//input[#class='nav-submit-input']")).click();
driver.findElement(By.xpath("//h2[#class='a-size-medium s-inline s-access-title a-text-normal' and contains(text(), \"Fbt Men's 8876 Casual Shoes\")]")).click();
}
}
I think this is like a Hello World for Selenium for you, you could make use defined methods in Java using Junit with the following annotations which can be found here
But as per norms we usually have a #Before method in Junit or #BeforeTest method in testng for setting up the webdriver and the url of AUT, also in your code a couple of xpaths were wrong which were causing the error, Please find below the correct working code with comments:
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
public class snapdeal {
public WebDriver driver;
#Before
public void setUP()
{
// I want open browser in function 1
driver= new SafariDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://amazon.in");
driver.manage().window().maximize();
}
#Test
public void test() {
// Function 2 for searching
//driver.findElement(By.xpath("//li[#id='nav_cat_2")).click(); //element not needed
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Shoes");
driver.findElement(By.xpath("//input[#class='nav-submit-input']")).click();
driver.findElement(By.xpath("//*[#title=\"Fbt Men's 8876 Casual Shoes\"]//h2")).click();
}
}
The above code works as desired.
Creating user defined function have two different scope
1) Create function with piece of code and call that function whenever u needed it (Which is done above)
2) Second one creating a custom function wrt each controls like edit boxes , radiobutton , check boxes - etc , so by creating this functions u can make better feasible of your automation framework

Categories