Welcome to this tutorial. Let me begin by explaining the idea and what topics I would like to cover in this helpful how-to guide.

I’m aware that there is a lot of blogs about Selenium. It is not surprising because in my opinion Selenium has become the most popular tool for automated testing of web applications.

Selenium is free, easy to learn and really quickly we can create a bunch of automated tests. But over the time when number of tests grow significantly we need something more. Something that will allow us to easily manage and maintain our test repository. That’s why we need test automation framework.

As I mentioned earlier there is a lot of blogs about Selenium so you might wonder why I decided to create another one. Well, I would like to show you some design patterns and good practices that will help you to start with your own implementation of really basic test automation framework.

In several parts I will guide you step by step how to create it from a scratch. Each part will be published regularly and will contain some examples how to develop your framework. I know that it won’t be possible to cover all topics, but let start with some basics. Below is the initial plan for upcoming posts:

  • The first tests
  • Page Object Pattern
  • Dependency Injection with Guice
  • Hamcrest assertions

I think it would be a good start to understand the basic concepts necessary for a well-implemented automation framework. After that we can think about the next topics and there is a plenty to choose from. What you need for this tutorial? Basically you should have some understanding of Selenium automation and also programming skills in Java.

I will also encourage you to do something more on your own. Each part of this tutorial will contain some assignment for you but it won’t be published or evaluated in any way. Of course this assignment is optional and it’s only for you to develop your skills. After each section you can find actual version of project on GitHub, so you can compare it with yours results.

Setting up the environment

First things first. Before you begin to write any code you need to set up your development environment. As I mentioned previously, we are going to write our Selenium code in Java.

I believe that Java is the most frequently chosen language to write automation tests with Selenium, because of the great community and support. However, it is always good to be consistent, so if application under tests is written in C#, PHP or Python you should consider the choice of language to be the same. To resolve dependencies like Selenium or TestNG in our project we will use Maven.

Test automation framework will be based on TestNG. TestNG is a testing framework similar to JUnit and NUnit. I will be using IntelliJ Idea as my IDE, but of course it’s optional for you. You can use Eclipse if you prefer, but all examples have been prepared in IntelliJ Idea.

You can find some helpful instructions  on how to set up Eclipse environment under this link: Your first test in Java vs TestNG vs WebDriver vs Maven in Eclipse by Oleksandr Perepelytsya. Below you can find some instructions how to set up your IntelliJ Idea environment on Windows.

Java

1. Check if you have Java installed
1.1. Click Start, search for “cmd” and press Enter.
1.2. Type command: java –version
auto_fwk_blog_011.3. If you can see screen similar to above it means that Java is already installed and you can skip the installation. If Java is not found then proceed with instruction.

2. Download the installer
2.1. Open http://www.oracle.com/technetwork/java/javase/downloads/index.
2.2. Click “Download” button next to JDK in Java SE 7 section

auto_fwk_blog_022.3. Select “Accept License Agreement” and download JDK 7 for your version of Windows (32 or 64 bit)

auto_fwk_blog_033. Run the JDK Installer
4. Update the PATH Environment Variable
4.1. Click Start, then Control Panel, then System.
4.2. Click Advanced, then Environment Variables

auto_fwk_blog_044.3. Add the location of the bin folder of the JDK installation to the PATH variable in System Variables. The following is a typical value for the PATH variable: C:\WINDOWS\system32; C:\Program Files\Java\jdk1.7.0_75\bin

auto_fwk_blog_05auto_fwk_blog_065. Repeat steps from 1. to verify java has been installed

Download & install IntelliJ IDEA

1. Download Intellij IDEA
1.1. Open url: https://www.jetbrains.com/idea/download/
1.2. Download Community Edition
2. Run the Intellij IDEA installer

Create new project

1. Click “Create new project” on Welcome screen
auto_fwk_blog_072. Select “Maven” and Project SDK: 1.7 and then click on “Next” button

auto_fwk_blog_083. Fill in fundamental unit of work in Maven (POM). A POM requires that its groupId, artifactId, and version be configured:

  • groupId – the id of the project’s group.
  • artifactId – the id of the artifact (project)
  • version – the version of the artifact under the specified group

You can fill in those with data as below or you can use your own. Click “Next” button at the end.
auto_fwk_blog_094. Enter project name and location. Click “Finish” button.
auto_fwk_blog_10

5. At this point new project should be created. Click “Enable Auto-Import” if you want IntelliJ to import Maven projects automatically each time you change your pom.xml.

auto_fwk_blog_11auto_fwk_blog_126. Add Selenium and TestNG to your maven dependencies in pom.xml. In pom.xml add dependencies section as below:

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.45.0</version>
        </dependency>
    </dependencies>

After that your pom.xml should look like:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.pguzdziol.automation.tutorial</groupId>
    <artifactId>auto-fwk-tutorial</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.45.0</version>
        </dependency>
    </dependencies>
</project>

The first test

Now you should be ready to implement your first test because at this point you should have fully configured development environment. First and most important our application under tests is www.amazon.com. Probably you know it very well. Amazon is the most popular and the largest online store. I chose this web application because it gives us many possible test scenarios. I will show you how to implement sample test scenario and I hope that you will give a try to create second one on your own.

Create test class: First Tests

Let’s move forward and create your first test class, but before that let’s create a new package to properly organize the code. To do so, right mouse click on src\test\java inside the project and then New -> Package.

auto_fwk_blog_13Now you are asked to enter new package name. You can use my naming convention, but if you feel confident you can try to come up with your own.
auto_fwk_blog_14

Already created package should be displayed under java. We can create new class inside this package in almost exact same way, just select Java Class instead of Package. Right mouse click on the package name com.github.pguzdziol.automation.tutorial.tests and then New -> Java Class. Enter the class name which you want (in my example: FirstTests) and click Ok button.

auto_fwk_blog_15auto_fwk_blog_16If everything is fine you should be able to see similar code as below in Editor Window.

package com.github.pguzdziol.automation.tutorial.tests;

public class FirstTests {

}

Now you can start writing the code for your test. Firstly you need to create a new instance of WebDriver so you can use it in your test methods. You are going to do this in setUp() method annotated with @BeforeClass. @BeforeClass is TestNG annotation and it means that the annotated method will be run before the first test method in the current class is invoked. Go ahead and declare WebDriver instance variable and next initialize Firefox driver in setUp() as following:

package com.github.pguzdziol.automation.tutorial.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;

public class FirstTests {

    private WebDriver driver;

    @BeforeClass
    private void setUp() {
        driver = new FirefoxDriver();
    }
}

You have setUp() method ready but you also need tearDown() method to close browser window and safely end the session after all.

    @AfterClass
    private void tearDown() {
        driver.quit();
    }

Add above method inside your FirstTests class. @AfterClass annotation means that the method will be run after all the test methods in the current class have been run. To close browser window and end the session call driver.quit(). There is also another method driver.close() which close the browser window that the driver has focus of.

As I mentioned previously you are going to create some tests for www.amazon.com. If everything is fine setUp() method should open Firefox browser. Next step is to get Amazon page. Before each test method in our test class we want to start on Amazon home page – that’s why we need a method annotated with @BeforeMethod as below:

    @BeforeMethod
    public void openHomePage(){
        driver.get("http://www.amazon.com");
    }

Basically, this piece of code takes you to Amazon home page before each test method. Let’s create empty test method for now to verify what has been done so far. Add new test() method with @Test annotation inside the class. At this point you should have:

package com.github.pguzdziol.automation.tutorial.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class FirstTests {

    private WebDriver driver;

    @BeforeClass
    public void setUp() {
        driver = new FirefoxDriver();
    }

    @BeforeMethod
    public void openHomePage(){
        driver.get("http://www.amazon.com");
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void test(){
        //TODO
    }
}

Now run this empty test method which basically do nothing but will help us to verify that everything is fine at this point. Right mouse click on test() method and then Run. If everything went as expected you should notice that the test passed.

auto_fwk_blog_18

Create test method: testAddingItemToCard()

Test steps:

The first proposed test scenario is for adding item to the cart. Step by step you are going to write code for it without going into too much detail. Please take a look at following steps and try to reproduce them manually.

  1. Open www.amazon.com
  2. Select “Books” from search category dropdown
  3. Enter search key: “Selenium”
  4. Click “Go” button
  5. Click the first search result item title
  6. Verify that product title is correct
  7. Click “Add to Cart” button
  8. Verify confirmation test appears: “1 item added to Cart”
  9. Navigate to Cart page from main menu
  10. Verify item is displayed on Shopping Cart list

Locate elements on page

Before we start I would like to shortly explain how we can locate elements on the page with Selenium. There are several ways to locate those elements. We can find them by their attributes like id, name or class, but also we can find them by more flexible methods like xpaths or cssSelectors. More about those you can find in official Selenium documentation at „Locating UI Elements (WebElements)”: http://docs.seleniumhq.org/docs/03_webdriver.jsp.

In general all of them are based on HTML DOM. There are a lot of useful browser plugins and tools that can help us to find elements locators. Modern browsers have built-in developer tools for this assignment. In Firefox press F12 to open it and go to “Inspector” tab. Try it on your own just to get familiar with how it works.

auto_fwk_blog_17

testAddingItemToCard()

Go back to IDE and change the name of test() method to testAddingItemToCard(). Then step by step add below code inside this method.

  1. Open www.amazon.com – step is already implemented in openHomePage()
  2. Select “Books” from search category dropdown – We are going to use Select class. Select class is a helper for dealing with select tags.  Create new instance of Select class, but do not assign it to any variable. Select class constructor takes web element attribute. We can find this element by its id: “searchDropdownBox”. Then we select option “Books” using selectByVisibleText(String option) method.
        new Select(driver.findElement(By.id("searchDropdownBox")))
                .selectByVisibleText("Books");
    
  3. Enter search key: “Selenium” – Find search input field by its id and then enter “Selenium” into it.
        driver.findElement(By.id("twotabsearchtextbox"))
                .sendKeys("Selenium");
    
  4. Click “Go” button – Find “Go” button by its xpath and then click on it. Given xpath stands for first element with value attribute equals “Go”.
        driver.findElement(By.xpath("//*[@value='Go']"))
                .click();
    
  5. Click the first search result item title – In below code we are doing three things. Firstly we create local variable for item title element founded by its class name. Secondly we save item title text to local string variable so we can use it further. And lastly we click on item title element.
        WebElement firstItemTitleElement = driver.findElement(By.className("s-access-title"));
        String firstItemTitle = firstItemTitleElement.getText();
        firstItemTitleElement.click();
    
  6. Verify that product title is correct – Now it is time for the first assertion. Assertion expects that given statement returns true. Otherwise it cause the test to fail. We want to verify that the product title on product details page is equal to variable from previous step 5.
        assert (driver.findElement(By.id("productTitle"))
                .getText()
                .equals(firstItemTitle));
    
  7. Click “Add to Cart” button
        driver.findElement(By.id("add-to-cart-button"))
                .click();
    
  8. Verify confirmation test appears: “1 item added to Cart”
        assert (driver.findElement(By.id("confirm-text"))
                .getText()
                .equals("1 item added to Cart"));
    
  9. Navigate to Cart page from main menu
        driver.findElement(By.id("nav-cart"))
                .click();
    
  10. Verify item is displayed on Shopping Cart list
        assert (driver.findElement(By.className("a-list-item"))
                .getText()
                .contains(firstItemTitle));
    

As the result of all the above steps your final test method should look the following way:

@Test
public void testAddingItemToCard() {
    //Select 'Books' from search category dropdown
    new Select(driver.findElement(By.id("searchDropdownBox")))
            .selectByVisibleText("Books");

    //Enter search key: 'Selenium'
    driver.findElement(By.id("twotabsearchtextbox"))
            .sendKeys("Selenium");

    //Click 'Go' button
    driver.findElement(By.xpath("//*[@value='Go']"))
            .click();

    //Click the first search result item title
    WebElement firstItemTitleElement = driver.findElement(By.className("s-access-title"));
    String firstItemTitle = firstItemTitleElement.getText();
    firstItemTitleElement.click();

    //Verify product title
    assert (driver.findElement(By.id("productTitle"))
            .getText()
            .equals(firstItemTitle));

    //Click 'Add to cart' button
    driver.findElement(By.id("add-to-cart-button"))
            .click();

    //Verify confirmation text appears
    assert (driver.findElement(By.id("confirm-text"))
            .getText()
            .equals("1 item added to Cart"));

    //Navigate to 'Cart' page
    driver.findElement(By.id("nav-cart"))
            .click();

    //Verify item is displayed on Shopping Cart list
    assert (driver.findElement(By.className("a-list-item"))
            .getText()
            .contains(firstItemTitle));
}

Now run it (Right mouse click on testAddingItemToCard () and then Run). The test should pass.

Assignment 1

I hope that you have done above example without any serious issues. I strongly encourage you to train your skills now on your own by doing this assignment.  Below you will find proposed test scenario for basic sign in and sign out functionality. Start by reproducing those steps manually.

Then step by step implement each step from the scenario inside new test method in already created FirstTests class. In case of any issues try to find solution at Selenium documentation or Stack Overflow. It’s almost sure that you will find the answer there. After all you will find my solution of this assignment on github.

Create test method: testSignInSignOut()

Test steps:

  1. Open www.amazon.com
  2. Click ‘Your Account’ on main menu
  3. Enter email address:  automation.user2015@gmail.com
  4. Enter password: @ut0m@t!0n
  5. Click ‚Sign in using our secure server’ button
  6. Verify ‚Your Account’ button contains the name of the user
  7. Hover over a „Your account” button and click on „Sign Out”
  8. Verify ‘Sign In’ form appears

Summary

In this part we have configured development environment by installing Java and IntelliJ IDEA. Next we have created new maven project and we added required dependencies like Selenium and TestNG to it. After that we were ready to create our first test. I showed you how to implement sample test for adding item to card in Amazon online store.

You have learned some really basic Selenium methods that allowed you to interact with web browser. Also I asked you to create the second test on your own. Your assignment was to create test for Sign In and Sign Out functionality. At this point you should have single test class with two test methods inside. Final code for this part can be found on GitHub: https://github.com/pguzdziol/auto-fwk-tutorial/tree/blog-01/the-first-tests.

In next part you will learn about Page Object Pattern. I will show you how to refactor the code to use page objects. See you in next part!