Jeff Nyman
Jeff Nyman

Reputation: 890

Accessing Instance Variables in Helper Classes

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.

Upvotes: 4

Views: 1590

Answers (2)

Jeff Nyman
Jeff Nyman

Reputation: 890

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.

Upvotes: 0

Jeremiah
Jeremiah

Reputation: 1145

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."));
  }
}

Upvotes: 1

Related Questions