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
Related
everyone, I'm struggling with the following situation.
Returned driver is not recognized.
I want to make a method to used it for rest of the methods for a test suite but
package acceptanceTesting
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeSuite;
public class LoginTestingStep {
#BeforeSuite
public static WebDriver driver() {
System.setProperty(WebDriverPage.webDriverAdress, WebDriverPage.webDriverPath);
WebDriver driver = new ChromeDriver();
driver.get("https://evernote.com/");
return driver;
}
public static void WaitForElementVisible(String option) {
WebDriverWait wait = new WebDriverWait(driver(), 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(option)));
}
#Test
public static void UnauthotisedLogin() {
driver.manage().window().maximize();
driver.findElement(By.cssSelector(LoginTestingPage.loginButton)).click();
driver.findElement(By.cssSelector(LoginTestingPage.emailAdreesField)).sendKeys("spacesiatat#yahoo.com");
WaitForElementVisible(LoginTestingPage.continueButton);
driver.findElement(By.cssSelector(LoginTestingPage.continueButton)).click();
// TimeUnit.SECONDS.sleep(5);
// driver.close();
}
public static void AuthotisedLogin() {
}
}
Simple advice first: Do not make return anything when using TestNG annotations (like #BeforeSuite and etc.) Because everytime you want to call this method as parameter it will open new Chrome Browser.
Since you are creating driver in the inside of driver() method
No any other methods can see that there is driver already defined. Insted use it like global variable, not inside method.
public class LoginTestingStep {
WebDriver driver; //declare as global
#BeforeSuite
public static void driver() {
System.setProperty(WebDriverPage.webDriverAdress,
WebDriverPage.webDriverPath);
driver = new ChromeDriver(); //then create instance
wait = new WebDriverWait(driver, Duration.ofSeconds(5));
driver.get("https://evernote.com/");
}
public static void WaitForElementVisible(String option) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(option)));
}
#Test
public static void UnauthotisedLogin() {
driver.manage().window().maximize();
driver.findElement(By.cssSelector(LoginTestingPage.loginButton)).click();
driver.findElement(By.cssSelector(LoginTestingPage.emailAdreesField)).sendKeys("spacesiatat#yahoo.com");
WaitForElementVisible(LoginTestingPage.continueButton);
driver.findElement(By.cssSelector(LoginTestingPage.continueButton)).click();
}
}
**What I changed in your code? **
Made driver() method to be return type void instead of WebDriver return type
Deleted line that include: return driver;
Made WebDriverWait global to enable using it in other methods as well and avoiding repeating creating instance of it every time
Added 'DurationOfSeconds' to 'WebDriverWait' constructor parameter since raw usage of second is deprecated
I want to create a class where I set all the common actions of the WebDrivers such as: waitExplicit, findElement, click. But if I create a method then I have to create the WebDriver and WebDriverWait over and over on each method of the class, I already tried having a class for the Drivers, but when I call the methods, they just create instances over and over, so multiple windows open, I tried this way, but still cannot get to it:
public class AutomationActions{
static LoadProperties prop = new LoadProperties(); //This class has the System.setProperty for the driver
prop.getSysProp(); //***This is the issue, how can I solve this?****
WebDriver driver = new ChromeDriver(); //this will not work without the one above working
WebDriverWait wait = new WebDriverWait(driver, 30);//this will not work without the one above working
public void waitForPageToLoad() throws Exception {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
// WebDriverWait wait = new WebDriverWait(driver, 30); // I want to avoid having to set this in every method
wait.until(pageLoadCondition); //this is supposed to replace the line of code above
}
I don't really work on Java much any more, I've written our framework in C# but I put together some quick classes in Java to show you how I set things up. I use page object model and I recommend you do too so I've written this example using page object model. I've written a simple test that uses Dave Haeffner's (one of the Selenium contributors) demo site, http://the-internet.herokuapp.com.
The basic concepts are:
There is a class BaseTest that holds things that correspond to tests, e.g. setting up the driver at the start of the test, quitting the driver at the end of the test, etc. All of your tests will inherit from BaseTest
There is a class BasePage that holds things that correspond to generic methods for finding elements, clicking on elements, etc. Each of your tests inherit from BasePage. (This is what I think the main part of your question is asking about).
To follow the page object model, each page (or part of a page) is its own class and holds all locators and actions done on that page. For example, a simple login page would have the locators for username, password, and the login button. It would also hold a method Login() that takes a String username and a String password, enters those in the appropriate fields and clicks the Login button.
The final class of this example is a sample test aptly named SampleTest.
You shouldn't have any FindElements() or related calls in your tests, all those should be in the appropriate page object.
This is using TestNG as the unit test library. Use it or JUnit, your preference but if you use JUnit, you will need to change the asserts and the annotations.
Under 'src', I create a folder for page objects, 'PageObjects', and a folder for tests, 'Tests'. Here's what the files look like on disk.
\src
\PageObjects
BasePage.java
DropdownListPage.java
\Tests
BaseTest.java
SampleTest.java
BasePage.java
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BasePage
{
private WebDriver driver;
private final int shortWait = 10;
public BasePage(WebDriver _driver)
{
driver = _driver;
}
public void ClickElement(By locator)
{
new WebDriverWait(driver, shortWait).until(ExpectedConditions.elementToBeClickable(locator)).click();
}
public WebElement FindElement(By locator)
{
return new WebDriverWait(driver, shortWait).until(ExpectedConditions.presenceOfElementLocated(locator));
}
// add more methods
}
DropdownListPage.java
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
public class DropdownListPage extends BasePage
{
private final By dropdownListLocator = By.id("dropdown");
public DropdownListPage(WebDriver _driver)
{
super(_driver);
}
public String GetSelectedOption()
{
return new Select(FindElement(dropdownListLocator)).getFirstSelectedOption().getText();
}
public void SelectOptionByIndex(int index)
{
new Select(FindElement(dropdownListLocator)).selectByIndex(index);
}
}
BaseTest.java
package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
public class BaseTest
{
public WebDriver driver;
public WebDriver GetChromeDriver()
{
System.setProperty("webdriver.chrome.driver", "C:\\Path\\To\\Chrome\\Driver\\chromedriver.exe");
return new ChromeDriver();
}
#BeforeTest
public void Setup()
{
driver = GetChromeDriver();
driver.manage().window().maximize();
driver.get("http://the-internet.herokuapp.com/dropdown");
}
#AfterTest
public void Teardown()
{
driver.close();
}
}
SampleTest.java
package Tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import PageObjects.DropdownListPage;
public class SampleTest extends BaseTest
{
#Test
public void SampleTestCase()
{
DropdownListPage dropdownListPage = new DropdownListPage(driver);
dropdownListPage.SelectOptionByIndex(1);
Assert.assertEquals(dropdownListPage.GetSelectedOption(), "Option 1", "Verify first option was selected");
}
}
You will need to create a project that contains Selenium for Java and TestNG. Download them and put them on your build path. Create the folder structure as described above and create each of these classes and copy/paste the contents into them. Now all you need to do is run SampleTest as a TestNG Test and it should go.
The test creates a new Chromedriver instance, navigates to the sample page, selects the first option in the dropdown, asserts that the dropdown text is correct, and then quits the driver.
That should get you started. There's a lot of info crammed into the above wall of text, let me know if you have some questions.
I am new to automation testing in Selenium and i am doing some basic automation testing such as searching for something in Google and then clicking on a link which is required from the search results.
The code below, which i have produced works up until i get to the testing method. I am unable to select a link from the Google search page but i am not being shown any errors on my console. So i setup a thread on this particular line and it mentioned it could find the link name however the link name is used in the html code as i have checked on Google inspect.
Am i missing something obvious? I am relatively new to Selenium so any help is appreciated. Also i have tried mirroring some code from this users response "How to click a link by text in Selenium web driver java" but no luck!
Thanks
package com.demo.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class MyFirstTestScript {
private static WebDriver driver;
public static void main (String[] args) {
SetUp();
testing();
}
// TODO Auto-generated method stub
#setup
public static void SetUp () {
driver = new FirefoxDriver();
driver.get("http://www.google.co.uk");
System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}
#Test
public static void testing() {
driver.findElement(By.partialLinkText("BBC - Home")).click();
}
}
Once you obtain the search results for the text BBC on Google Home Page next to click() on the link containing the text BBC - Home you can use the following code block :
List <WebElement> my_list = driver.findElements(By.xpath("//div[#id='rso']//div[#class='rc']/h3[#class='r']/a"));
for (WebElement item:my_list)
{
if(item.getAttribute("innerHTML").contains("BBC - Home"))
item.click();
}
You can use this code:
public class MyFirstTestScript {
private static WebDriver driver;
private static WebDriverWait wait;
public static void main (String[] args) {
SetUp();
testing();
}
#setup
public static void SetUp () {
System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
driver = new FirefoxDriver();
wait = new WebDriverWait(driver,50);
driver.manage().window().maximize();
driver.get("http://www.google.co.uk");
wait.until(ExpectedConditions.elementToBeClickable(By.name("q")));
driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}
#Test
public static void testing(){
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.linkText("BBC - Homepage"))));
driver.findElement(By.linkText("BBC - Homepage")).click();
}
I just created a sample project using Serenity + cucumber + java + maven ( > mvn archetype:generate -Dfilter net.serenity-bdd:serenity-cucumber) .
I can see when it brings up a firefox browser and goes to this website:
#DefaultUrl("http://en.wiktionary.org/wiki/Wiktionary")
Question:
From this point, a "WebDriver driver" was created, but how can I obtain/get to that "driver" variable ? I'm trying to get the window ID using driver.getWindowHandle().
Updated: The statements are as followed:
#DefaultUrl("http://en.wiktionary.org/wiki/Wiktionary")
public class DictionaryPage extends PageObject {...}
I looked up the PageObject super class and found this:
public abstract class PageObject extends net.serenitybdd.core.pages.PageObject {
protected PageObject() {
super();
}
protected PageObject(WebDriver driver, Predicate<? super net.serenitybdd.core.pages.PageObject> callback) {
super(driver, callback);
}
public PageObject(WebDriver driver, int ajaxTimeout) {
super(driver, ajaxTimeout);
}
public PageObject(WebDriver driver) {
super(driver);
}
}
So.. the PageObject uses the webdriver variable from another super class. What is the syntax I need to declare to get to this "web driver" variable?
Thanks
Know-nada
=========================
JDelorean!
Thanks a lot for your help. Here are the codes.. Would you please help tp point out what is wrong with the "driver"?
1 - Feature File:
Feature: Amazon user login authentication
Scenario: Amazon user login authentication
Given user is on the "home" page
2 - Step Definitions File:
package com.XXXX.steps;
import net.thucydides.core.annotations.Steps;
import com.XXXX.steps.serenity.User;
import cucumber.api.java.en.Given;
class DefinitionSteps {
#Steps
User user;
#Given("^user is on the \"([^\"]*)\" page$")
public void user_is_on_the_Amazon_page(String pageName)throws Throwable{
user.is_on_the_page(pageName);
}
}
3 - Test Runner class
package com.XXXX;
import cucumber.api.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;
#RunWith(CucumberWithSerenity.class)
#CucumberOptions(features="src/test/resources/features")
public class DefinitionTestSuite {
}
4 - The User Class where I am not able to capture the driver. Please note that at the end of this file, the commented out line is the one that does not work. Also notice that the "driver" was set to the original driver "home.getDriver()" but somehow that value was passed to the "driver" but the driver "home.getDriver()" works just fine.
package com.XXXX.steps.serenity;
import com.XXXX.pages.Home;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.steps.ScenarioSteps;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class User extends ScenarioSteps{
Home home = new Home();
WebDriver driver = home.getDriver();
#Step
public void is_on_the_page(String pageName) throws Throwable {
home.open();
home.getDriver().findElement(By.xpath(home.homeElements.get("Hello. Sign in"))).click();
// driver.findElement(By.xpath(".//*[#id='nav-link-yourAccount']/span[1]")).click();
}
}
PageObject has a getDriver() method, which you should use if you require the use of WebDriver.
I strongly suggest you study the Serenity BDD's Manual if you are going to work with the framework. You should find an answer to most questions there. Alternatively, check Serenity BDD Users Group.
This can be achieved following way.
WebDriver driver = Serenity.getDriver();
driver.findElement(By.xpath....);
For some unknown reason, the Serenity-BDD:Cucumber framework does not allow you to assign its driver to your local variable.
This assignment statement WebDriver driver = getDriver(); will result in a null pointer in the "driver" local variable.
My guess is that the framework needs to protect its getDriver() because it needs to do report on snapshots and scenarios steps.
So you have it. simply use the framework's getDriver() and you can drive from page to page without any problem at all as long as you declare your page class as an extension of the base/Abstract class PageObject.
An example of your page class:
public void HomePage extends PageObject {
}
At the time you instantiate the HomePage class HomePage homePage; the framework's driver is automatically attached to the homePage.
Let say you want to click on an element, you simply state:
getDriver().findElement(By.xpath("locationOfTheTargetElement").click();
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