Monday, December 8, 2014

Selenium WebDriver with Java - Create Helper Classes (1)

Introduction

In this article we will start presenting a Selenium WebDriver framework. The following are used:
- Java
- Intellij IDEA 14 Community edition IDE
- Junit for tests
- maven
- log4j library for logging
- Hudson for continuous integration
In a future article we will present how to install and integrate all these components.

DriverUtils

First of all we can create a DriverUtils class that will contain functions for starting the web driver, getting the browser, opening the desired url, closing browser, login, logout, functions to be executed before and after all tests are run or after all test from a class are run. Also, we can include here a function that will log, at the beginning of each test, a name and a description.
Let's start!

Start WebDriver

public static void open_driver(String bName)
{
    logger.info("Opening selenium driver");
    selenium = null;
    String path = System.getProperty("user.dir");

    if(bName.equals(ConstantsHelpers.firefoxBrowser))
    {
        FirefoxProfile firefoxProfile = new FirefoxProfile();
        selenium = new FirefoxDriver(firefoxProfile);
        selenium.manage().window().maximize();
    }
    else if(bName.equals(ConstantsHelpers.ieBrowser))
    {
        DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
        caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        System.setProperty("webdriver.ie.driver", path + "\\IEDriver\\IEDriverServer.exe");
        selenium = new InternetExplorerDriver(caps);
        selenium.manage().window().maximize();
    }
    else if(bName.equals(ConstantsHelpers.chromeBrowser))
    {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-web-security");
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        caps.setCapability(ChromeOptions.CAPABILITY, options);
        System.setProperty("webdriver.chrome.driver", path + "\\ChromeDriver\\chromedriver.exe");
        selenium = new ChromeDriver(caps);
        selenium.manage().window().maximize();
    }

    else if(bName.equals(ConstantsHelpers.safariBrowser))
    {
        selenium = new SafariDriver();
        selenium.manage().window().maximize();
    }
}

Some tips about this function:
  • selenium is declared globally

public static WebDriver selenium;
  • selenium is set and get
//Function to get selenium driver
public static WebDriver getSelenium() { return selenium; }
//Function to set selenium driver
public static void setSelenium(WebDriver selenium) { DriverUtils.selenium = selenium;}
  • for working with Chrome and IE drivers we need to download the exe drivers and include them in the project. To set the path we use
String path = System.getProperty("user.dir");
  • The name of the drivers are stored in a ConstantsHelpers class 
public static String ieBrowser = "IE";
public static String firefoxBrowser = "Mozilla";
public static String safariBrowser = "Safari";
public static String chromeBrowser = "Chrome";
  • Capabilities: describes a series of key/value pairs that encapsulate aspects of a browser. You can find more information about this on the internet
Get browser
//Browser type: change constant if you want to run test on different browser//Available browsers are: IE, Chrome, Firefox, Safaripublic static String getBrowser() {
    return ConstantsHelpers.firefoxBrowser;
    //return ConstantsHelpers.chromeBrowser;    //return ConstantsHelpers.ieBrowser;    //return ConstantsHelpers.safariBrowser;
}

Open url

In order to open your url you can create a function
//Function that opens the desired url for your applicationpublic static void open_url()
{
    logger.info("Opening url " + ConstantsHelpers.url);
    selenium.get(ConstantsHelpers.url);
}

where the url is define in a ConstantsHelpers class
public static String url="http://my_url.com";

Close browser
//Closes browser/driverpublic static void close_browser()
{
    logger.info("Closing browser and driver");
    getSelenium().close();
    getSelenium().quit();
}

Wait time 
This is a function used to implicitly wait the specified amount of time in milliseconds
public static void wait_time(long fWait){
    try {
        Thread.sleep(fWait);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

You can use it like this:
wait_time(5000);

@Before, @BeforeClass, @AfterClass, @After
Depending on your project, you can set some actions to be taken:
- before starting tests @Before
- before starting tests from a class @BeforeClass
- after running all tests from a class @AfterClass
- after running all tests @After

Here are some examples:
@BeforeClassstatic public final void setUpBeforeClass() throws Exception {
    String browser = DriverUtils.getBrowser();
    open_driver(browser);
}

@Beforepublic void setUp() throws Exception
{
    open_url();
}

@AfterClassstatic public void tearDownAfterClass() throws Exception
{
    close_browser();
}

Login, Logout
Supposing you web page has a login page, you can include the Login, Logout function in @BeforeClass and @AfterClass annotations.
Below you have a login example:
public static void login(String username, String password) {
    logger.info("Logging in with '" + username + "' userName and language " + password);

    ControlUtils.send_keys(By.id("language-select"), ConstantsHelpers.language);
    ControlUtils.send_keys(By.id("username"), username);
    ControlUtils.send_keys(By.id("password"), password);

    ControlUtils.fluentWait(By.id("loginBtn")).click();
}

Test Case Description
Another function that we added in this class is the one that, in the test logs, at the beginning of each test, writes a brief description about the test to be run.
public static void TestCaseDescription(String title, String description)
{
    String browser=DriverUtils.getBrowser();

    logger.info("---------------------------------------------------------------------");
    logger.info("This test was executed in '" + browser + "' browser.");
    logger.info("---------------------------------------------------------------------");
    logger.info("Test executed in class '" + StackTraceInfo.getInvokingClassName() + "' and in method '" + StackTraceInfo.getInvokingMethodName() + "'.");
    logger.info("---------------------------------------------------------------------");
    logger.info("Test title '" + title + "'.");
    logger.info("---------------------------------------------------------------------");
    logger.info("Test description '" + description + "'.");
    logger.info("---------------------------------------------------------------------");
}

The function uses log4j library and a class for getting the class and method name. But we will talk about these in future stories
The function can be used like this: TestCaseDescription("Test name", "Test description");
and the result in the test run will look like this:

Hope you enjoyed this article.

No comments:

Post a Comment

Popular Posts