I'm trying to use only PageFactory in my project, without using fields with type By. And I'm looking to implement something like this:
#FindBy(className = "loading-container")
private WebElement loadingElement;
public LoadingPage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.waitDriver = new WebDriverWait(this.driver, 20);
}
public void waitLoadingToFinish() {
this.waitDriver.until(ExpectedConditions.elementNotExists(loadingElement));
}
Is there a way to implemet custom Expected Condition for this? or any other way to implement this? (without using By fields, only using page factory).
As far as I understand you have some elements on the page that you consider ready for usage only when there is no certain element on the page (like waiting wheel).
There is a special locator class in Selenium called AjaxElementLocator. What you need to do is to extend that type by changing isElementUsable method when you initialize your page so that all the controls you use on that page would first check the condition. Here is the example:
package click.webelement.pagefactory.conditions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocator;
public class LoadablePage {
#FindBy(id = "cntrl-id")
WebElement control;
public LoadablePage(WebDriver driver){
PageFactory.initElements(field -> new AjaxElementLocator(driver, field, 10){
#Override
protected boolean isElementUsable(WebElement element) {
return driver.findElements(By.xpath("//WHEEL_XPATH")).size() == 0;
}
}, this);
}
}
Here you can find more information on such approach.
Selenium has this method
ExpectedConditions.InvisibilityOfElementLocated
An expectation for checking that an element is either invisible or not
present on the DOM.
For your code
public void waitLoadingToFinish() {
this.waitDriver.until(ExpectedConditions.invisibilityOfElementLocated(loadingElement));
}
also, you might try to add a javascript executor to wait until the page is loaded
public static void waitForScriptsToLoad(WebDriver driver) {
WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd ->
((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
}
and then your page constructor becomes this
public LoadingPage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.waitDriver = new WebDriverWait(this.driver, 20);
waitForScriptsToLoad(driver);
}
If you create wait method in your program that is easy and customize in selenium framework
private static WebElement waitForElement(By locator, int timeout)
{
WebElement element=new WebDriverWait(driver,timeout).until(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
//If you want wait for id following code should use
waitForElement(By.id(""),20);
Here 20 is miliseconds
and you can use any web elements to wait
To simulate an ExpectedConditions like elementNotExists you can use either among invisibilityOfElementLocated() or invisibilityOf().
invisibilityOfElementLocated()
invisibilityOfElementLocated() is the implementation for an expectation for checking that an element is either invisible or not present on the DOM. It is defined as follows:
public static ExpectedCondition<java.lang.Boolean> invisibilityOfElementLocated(By locator)
An expectation for checking that an element is either invisible or not present on the DOM.
Parameters:
locator - used to find the element
Returns:
true if the element is not displayed or the element doesn't exist or stale element
Code Block:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class fooPage {
WebDriver driver;
public fooPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
//you don't need this
//#FindBy(className = "loading-container")
//private WebElement loadingElement;
public void foo()
{
Boolean bool = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.className('loading-container')));
//other lines of code
}
}
As an alternative you can also use the invisibilityOf() method as follows:
invisibilityOf()
invisibilityOf() is the implementation for an expectation for checking the element to be invisible. It is defined as follows:
public static ExpectedCondition<java.lang.Boolean> invisibilityOf(WebElement element)
An expectation for checking the element to be invisible
Parameters:
element - used to check its invisibility
Returns:
Boolean true when elements is not visible anymore
Code Block:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class fooPage {
WebDriver driver;
public fooPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(className= 'loading-container')
WebElement loadingElement;
public void foo()
{
Boolean bool = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOf(fooPage.getWebElement()));
//other lines of code
}
public WebElement getWebElement()
{
return loadingElement;
}
}
You can find a detailed discussion in How to use explicit waits with PageFactory fields and the PageObject pattern
Related
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 wrote the below method in my Page.class for reusing implicit wait.
public WebDriver waitForElementToLoad(WebElement element)
{
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
return (driver);
}
In my test.class I am using page factory elements, for example:
//Save button
#FindBy(xpath = "//*[#*='Save']")
private WebElement saveButton;
Now I am trying to call:
waitForElementToLoad(saveButton);
from test.Class but I am getting below error.
"java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be
cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and
org.openqa.selenium.By are in unnamed module of loader 'app')"
I also tried
WebElement saveButton = driver.findElement(By.xpath("//*[#*='Save']"));
waitForElementToLoad(saveButton);
but no luck.
How can I make this work?
WebDriverWait is explicit wait, not implicit. And you can't cast WebElement to By.
If saveButton is not null than it was already found by the page factory, waiting for it presence is meaningless, that's why you don't have an overload with WebElement. Wait for visibility instead
wait.until(ExpectedConditions.visibilityOf(element));
If you need to use ExpectedConditions with some your "Page" class that contains asynchronously loaded elements I would recommend to use the following approach:
Extend AjaxElementLocator where override protected boolean isElementUsable(WebElement element) so that it uses ExpectedConditions to decide if the element is ready for use
Extend AjaxElementLocatorFactory where override public ElementLocator createLocator(Field field) method so that it now returns the instance of your extended class
Where you initialize elements use PageFactory.initElements(new MyAjaxElementLocatorFactory(driver, 10), this); where MyAjaxElementLocatorFactory is the class that you created on step 2
This error message...
java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and org.openqa.selenium.By are in unnamed module of loader 'app')
...implies that the ClassCastException occured while trying to cast a proxy object.
You need to consider a few things as follows:
The wait you introduced within waitForElementToLoad() isn't implicit wait as such but an ExplicitWait. See: What is the internal working difference between Implicit Wait and Explicit Wait
presenceOfElementLocated() doesn't garuntees the visibility or interactablity of any element. So for visibility or interactablity you need to use the matching ExpectedConditions either visibilityOf(WebElement element) or elementToBeClickable(By locator). For details, see: Selenium: How selenium identifies elements visible or not? Is is possible that it is loaded in DOM but not rendered on UI?
If your usecase involves inducing WebDriverWait you pass the WebElement saveButton in the form of a proxy object within waitForElementToLoad() as follows:
package com.pol.zoho.PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
//Save button
#FindBy(xpath = "//*[#*='Save']")
private WebElement saveButton;
public void waitForElementToLoad()
{
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
saveButton.click();
}
public WebElement getWebElement()
{
return saveButton;
}
}
Reference
You can find a couple of relevant discussions in:
How to add explicit wait in PageFactory in PageObjectModel?
How to wait for invisibility of an element through PageFactory using Selenium and Java
I'm performing Selenium automation in Java using POM. I need to highlight elements on the following web page. But it doesn't make any effect at all, though I don't get any error message, it simply doesn't highlight the element I've selected.
As I'm using POM pattern I have a separate class including all element functionality methods, such as click, write text, etc.
package pageObjects;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class BasePage {
public WebDriver driver;
public WebDriverWait wait;
// Constructor
public BasePage (WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, 15);
}
// Click Method
public void click (By elementBy) {
waitVisibility(elementBy);
driver.findElement(elementBy).click();
}
I have highlighting element method as following.
// Element highlighter method
public static void highLightElement(WebDriver driver, By elementBy) {
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", elementBy);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
js.executeScript("arguments[0].setAttribute('style','border: solid 2px white');", elementBy);
}
I have changed my click method as following.
public void click_2 (By elementBy) {
waitVisibility(elementBy);
highLightElement(driver,elementBy);
driver.findElement(elementBy).click();
}
And use it in a separate class with all page methods.
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class HomePage extends BasePage {
// Constructor
public HomePage (WebDriver driver) {
super(driver);
}
// Page Variables
String baseURL = "https://www.bookdepository.com/";
// Web Elements
// --- Sign In UI ---
By signInJoin_button = By.xpath("//div[#class='page-slide']//ul[#class='right-nav mobile-nav-content']//li[3]//a[1]");
By signOut_button = By.xpath("/html/body/div[4]/div[1]/div/ul[2]/li[5]/a");
// Page Methods ---
public HomePage goToBookDepositoryHomePage (){
driver.get(baseURL);
pause();
return this;
}
public LoginPage goToLoginPage (){
click_2(signInJoin_button);
pause();
return new LoginPage(driver);
}
What am I doing wrong here?
You should use WebElement and not By to change the style. Try following code:
public static void highLightElement(WebDriver driver, By elementBy) {
WebElement webElement = driver.findElement(elementBy);
String originalStyle = webElement.getAttribute("style");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]", webElement, "style", originalStyle + "border: 2px solid red;");
//Do something e.g. make a screenshot
//Reset style
js.executeScript("arguments[0].setAttribute(arguments[1], arguments[2])", webElement, "style", originalStyle);
}
I think it makes sense to keep the original style and just add the border. After doing something with the highlighted element e.g. creating a screenshot, you should reset the style. When you return the original style you could remove the reset part in a separate method.
Try the following code. This will highlight all the web elements of a test page.
I am using the EventFiringWebDriver to highlight the webelements in the below code.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;
import org.openqa.selenium.support.events.EventFiringWebDriver;
public class HighLighterEventListener extends AbstractWebDriverEventListener {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "./libs/chromedriver 4");
WebDriver webdriver=new ChromeDriver();
EventFiringWebDriver driver = new EventFiringWebDriver(webdriver);
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://yosuva.com");
driver.register(new HighLighterEventListener());
driver.findElement(By.xpath("//span[text()='Home']"));
driver.findElement(By.xpath("//span[text()='About']"));
driver.findElement(By.xpath("//span[text()='Tools']"));
driver.findElement(By.xpath("//span[text()='News']"));
driver.findElement(By.xpath("//span[text()='Events']"));
driver.findElement(By.xpath("//span[text()='Contact']"));
driver.quit();
}
#Override
public void afterFindBy(By by, WebElement element, WebDriver driver) {
((JavascriptExecutor)driver).executeScript(
"arguments[0].style.border='3px solid green'",element
);
}
}
I'm writing automated scripts using page factory and I want to use visibilityOfElementLocated with page factory instead of visibilityOf
I tried to use visibilityOf but some times it not work with my element
the problem here that visibilityOfElementLocated take By parameter, and I have WebElment
#FindBy(id = "test")
WebElement locator;
You can't use it directly with #FindBy, but you can call it from a method that will run before PageFactory.initElements
public abstract class BasePage {
protected WebDriverWait wait;
public BasePage(WebDriver driver) {
wait = new WebDriverWait(driver, 10);
assertInPage();
PageFactory.initElements(driver, this);
}
public abstract void assertInPage();
}
public class DerivedPage extends BasePage {
#FindBy(id = "test")
WebElement locator;
public DerivedPage(WebDriver driver) {
super(driver);
}
#Override
public void assertInPage() {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("test")));
}
}
assertInPage() in DerivedPage will be executed right before PageFactory.initElements.
visibilityOfElementLocated(By locator)
visibilityOfElementLocated(By locator) takes a __By locator_ as an argument and is the expectation for checking that an element is present on the DOM of a page and visible.
visibilityOf(WebElement element)
visibilityOf(WebElement element) takes an WebElement as an argument and is the expectation for checking that an element, known to be present on the DOM of a page, is visible.
When using PageFactory in PageObjectModel if you expect the element to be dynamic and loaded through some JavaScript and might not be present on the page already you can use the Explicit Wait support with a normal locator factory as follows:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestPage {
WebDriver driver;
//constructor
public TestPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
//Locator Strategy
#FindBy(id = "test")
WebElement locator;
//Test Method
public void testMethod()
{
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOf(TestPage.getWebElement()));
//perform your desired action here e.g element.click()
}
public WebElement getWebElement()
{
return locator;
}
}
You can find a detailed discussion in How to add explicit wait in PageFactory in PageObjectModel?
Disclaimer: I come from a dynamic language background (Ruby) and I'm trying to level up my skills in Java. I fear with my problem here I'm thinking too much in the context of Ruby and would appreciate some pointers.
Problem:
I want to see how I can have a helper class know about the existence of a WebDriver instance without having to pass the instance around all the time. The reason I'm trying to avoid that is because it leads to extra method arguments and less fluent test writing.
Context:
I have a test case (LoginIT.java) that looks like this:
package com.testerstories.learning.symbiote;
import static com.testerstories.learning.helpers.Selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class LoginIT {
WebDriver driver;
#BeforeTest
public void startBrowser() {
driver = new FirefoxDriver();
}
#AfterTest
public void quitBrowser() {
driver.quit();
}
#Test
public void loginAsAdmin() {
driver.get("http://localhost:9292");
withElement("open").click();
waitForPresence("username");
withElement("username").sendKeys("admin");
withElement("password").sendKeys("admin");
withElement("login-button").submit();
waitForPresence("notice");
assertThat(withElement("notice", "className"), equalTo("You are now logged in as admin."));
}
}
The key methods to note here are the calls to withElement and waitForPresence. These are defined on the Selenium class that I created and reference via the static import at the top.
Here is Selenium.java which contains that logic:
package com.testerstories.learning.helpers;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium {
public static WebElement withElement(String identifier, String locator) {
switch (locator) {
case "className":
return driver.findElement(By.className(identifier));
default:
return withElement(identifier);
}
}
public static WebElement withElement(String identifier) {
return driver.findElement(By.id(identifier));
}
public static void waitForPresence(String identifier, String locator) {
WebDriverWait wait = new WebDriverWait(driver, 10, 500);
switch (locator) {
case "className":
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(identifier)));
default:
waitForPresence(identifier);
}
}
public static void waitForPresence(String identifier) {
WebDriverWait wait = new WebDriverWait(driver, 10, 500);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(identifier)));
}
}
The key problem here are the lines that reference driver. When these methods were defined in LoginIT.java that wasn't an issue because WebDriver is defined there in the driver instance.
I do know that one answer to my problem is that I could just pass the WebDriver instance to each method. So, for example, I could use this method signature with withElement:
public static WebElement withElement(WebDriver driver, String identifier)
I'm adding another argument to pass in the WebDriver instance. But that means my test logic has to look like this:
withElement(driver, "username").sendKeys("admin");
withElement(driver, "password").sendKeys("admin");
withElement(driver, "login-button").submit();
Not the end of the world but it's less fluent and it just seems like there should be a better way.
Question:
Is there a better way?
Or am I in fact on the right track and should just accept that if I want the helper methods to be separate from the tests the driver reference must be passed in? And thus accept the slightly more verbose test statements?
Other Thought:
The only other thing I can immediately think of is that I create yet a third class that represents just WebDriver itself. This third class is then used by both my test (LoginIt.java) and my test helper (Selenium.java). I'm not sure how best to implement that but I'm also not sure if going that route makes sense.
I say that because it seems if I do that, I'm simply creating a class to wrap the creation of a WebDriver instance. So I have to create a class to then get an instance of that class so that I can create an instance of WebDriver. It seems like I'm adding complexity ... but maybe not. Hence my quest for pointers.
An alternative may be to allow your Selenium class to be initialized. Rather than having the methods be static, you can require the WebDriver reference in the class constructor.
package com.testerstories.learning.helpers;
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 Selenium {
private final WebDriver driver;
public Selenium(WebDriver webDriver) {
this.driver = webDriver;
}
public WebElement withElement(String identifier, String locator) {
switch (locator) {
case "className":
return driver.findElement(By.className(identifier));
default:
return withElement(identifier);
}
}
public WebElement withElement(String identifier) {
return driver.findElement(By.id(identifier));
}
public void waitForPresence(String identifier, String locator) {
WebDriverWait wait = new WebDriverWait(driver, 10, 500);
switch (locator) {
case "className":
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(identifier)));
default:
waitForPresence(identifier);
}
}
public void waitForPresence(String identifier) {
WebDriverWait wait = new WebDriverWait(driver, 10, 500);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(identifier)));
}
}
Your LoginIT.java would then initialize the reference with in the #Before along with the driver, and change the formerly static calls to the instance you stood up:
package com.testerstories.learning.symbiote;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.testerstories.learning.helpers.Selenium;
public class LoginIT {
WebDriver driver;
Selenium selenium;
#BeforeTest
public void startBrowser() {
driver = new FirefoxDriver();
selenium = new Selenium(driver);
}
#AfterTest
public void quitBrowser() {
driver.quit();
}
#Test
public void loginAsAdmin() {
driver.get("http://localhost:9292");
selenium.withElement("open").click();
selenium.waitForPresence("username");
selenium.withElement("username").sendKeys("admin");
selenium.withElement("password").sendKeys("admin");
selenium.withElement("login-button").submit();
selenium.waitForPresence("notice");
assertThat(selenium.withElement("notice", "className"), equalTo("You are now logged in as admin."));
}
}
I'm not entirely certain if this solution follows best design practices, but here is what I ended up doing. (Note: I changed from TestNG to JUnit but other than that, everything is functionally equivalent.)
I created a Driver.java class:
package com.testerstories.learning.helpers;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Driver {
private WebDriver driver;
public WebDriver getDriver() {
if (null == driver) {
driver = new FirefoxDriver();
}
return driver;
}
public void quitDriver() {
if (null != driver) {
driver.quit();
driver = null;
}
}
}
So this class is responsible for creating a driver instance and getting rid of that instance. It checks if the driver is null before creating so it won't keep creating new instances. Here I'm hard-coding a new instance of Firefox. Eventually I would have to make this class create new browser drivers based on what the user wants, but baby steps first.
Then I created DriverFactory.java which looks like this:
package com.testerstories.learning.helpers;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
public class DriverFactory {
private static Driver driver;
#Before
public void createDriver() {
driver = new Driver();
}
public static WebDriver getDriver() {
return driver.getDriver();
}
#After
public void quitDriver() {
driver.quitDriver();
}
}
This factory is used to create the driver instances. Notice the #Before and #After annotations. So this is where the tests have to rely on the driver factory. So what this means is that my tests now inherit the DriverFactory, whose responsibility is to provide an actual driver instance. So my LoginIT.java test now changes to this (continuing to use Jeremiah's provided solution as well):
package com.testerstories.learning.symbiote;
import com.testerstories.learning.helpers.DriverFactory;
import com.testerstories.learning.helpers.Selenium;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class LoginIT extends DriverFactory {
WebDriver driver;
Selenium selenium;
#Test
public void loginAsAdmin() {
driver = DriverFactory.getDriver();
selenium = new Selenium(driver);
driver.get("http://localhost:9292");
selenium.withElement("open").click();
selenium.waitForPresence("username");
selenium.withElement("username").sendKeys("admin");
selenium.withElement("password").sendKeys("admin");
selenium.withElement("login-button").submit();
selenium.waitForPresence("notice", "className");
assertThat(selenium.withElement("notice", "className").getText(), equalTo("You are now logged in as admin."));
}
}
I'm still doing some (all?) of the things that jpmc26 was concerned about and I can't honestly say I'm doing this well. But this does work.
If anyone has any thoughts -- particularly critical ones -- I'm most open to hearing them. As mentioned in my original question, I'm attempting to get better at Java after many, many years as a Ruby programmer. It's been rough going, to say the least.