Sushant

 

 

 

 

 

 Sushant Rawal

This tutorial assumes that you already have a script ready through Selenium or through Webdriver. Lately, with the advent of Test Driven Development (TDD) people have been looking to convert their Webdriver/Selenium IDE scripts to JUnit to gain the ability to consolidate development and testing code and compile testing code along with development stream and they have been struggling with some aspects. First let me clarify how different JUnit is from Selenium or Webdriver.

JUnit converts your Webdriver/Selenium IDE script into a more modular format. This gives you better control over which part of your web application you want to test. JUnit also plays a vital role in keeping the testing code tightly coupled with development code. This way changes to the testing code can be made frequently and can be tracked well for every development change. For this tutorial I will take an example of the Gmail login page. Let us first take into consideration that you have generated your scripts using Selenium IDE.

Selenium IDE – Go to File>Export Test Cases As and then select Java/Junit4/Webdriver.

1

You will see that it asks you for a filename and the location where you want to store the file. Give an appropriate name followed by the .java extension for the file. Once you save the file you will find it at the provided location. When you open the file you see a code which looks something like:

package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Login {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();

@Before

public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = “https://accounts.google.com/”;
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test

public void testLogin() throws Exception {
driver.get(baseUrl + “/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2”);
driver.findElement(By.id(“Email”)).clear();
driver.findElement(By.id(“Email”)).sendKeys(“youremail”);
driver.findElement(By.id(“Passwd”)).clear();
driver.findElement(By.id(“Passwd”)).sendKeys(“yourpassword”);
driver.findElement(By.id(“signIn”)).click();
driver.findElement(By.cssSelector(“span.gbmai”)).click();
driver.findElement(By.id(“gb_71″)).click();
}

@After

public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!””.equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}

In the above lines you will notice the @Before, @Test and @After tags. These tags define various parts of your test script execution. In the @Before tag you need to put in the opening of web browser and the URL that you want to load on the web browser.

The @Test tag defines your test case that you want to execute. You need to put @Test tag before every test case that you have defined to execute them. The other thing that you need to take care is to put all the test cases into appropriate methods and give them names according to the test case that you are executing which gives you a better idea of which test cases have passed or failed upon execution. More about the tags and functions in the next section.

The code generated in this fashion is ready-to-use and you can check it in your java project.

This was all about how you can convert your Selenium IDE script to JUnit Wedriver format. Now let us consider you have a Webdriver script that you have manually written for the above scenario and you want to convert it into JUnit format. If you have a Wedriver script it would look something like below:

import time;

from selenium import webdriver;
from selenium.webdriver.common.keys import Keys;

public class GmailLogin {

publie static void main String(args[]) {

Webdriver driver= webdriver.Firefox();
driver.get(“http://mail.google.com”);
WebElement emailid=driver.findElement(By.id(“Email”));
emailid.sendKeys(“yourgmailid”);
Webelement passw=driver.findElement(By.id(“Passwd”));
passw.sendKeys(“yourpassword”);
signin=driver.findElement(By.id(“signIn”));
signin.click();
time.sleep(10);
lout= driver.find_element_by_link_text(‘Sign out’);
lout.click();
}
}

The above script shows you how the Webdriver script looks & now to convert this script to a JUnit format you need to identify different parts of the script. The first part is the setup where you open the web browser and then point it the URL. But before that you need to import the junit package for using JUnit tags in your Webdriver script:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

Now you have to remove the main function (public static void main) as JUnit runs individual functions according to the start tag (@Before, @Test and @After) which is mentioned before each function that you create.

public class GmailLoginTest {
publie static void main String(args[]) {

P.s You need to remove the closing parenthesis too

 

You now need to segregate the individual steps in various modules which will be put under different tags that define your JUnit test. The first step is to put the opening of browser and redirection to the URL under the @Before tag with an appropriate function name. I have used setUp as the function name.

private Webdriver driver;
private final string GmailURL = “http://www.gmail.com”;

@Before

public void setUp() throws Exception() {
driver = new FirefoxDriver();
driver.get(GmailURL);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
}

The @Test is the tag where all your test scripts are to be put under. In my case I had to test the Login functionality of Gmail. You need to put it under a separate method. I have defined a method called LoginGmail and put the code of logging in inside this method.

@Test

public void LoginGmail() throws Exception {
driver.swtichTo().defaultContent();
WebElement userName = driver.findElement(By.id(“Email”);
userName.sendKeys(“youremail@gmail.com”);
WebElement password = driver.findElement(By.id(“Passwd”);
password.sendKeys(“yourPassword”);
driver.findElement(By.id(“signIn”).click();
}

Now in the end comes the @After tag where you usually close the Webdriver session by driver.quit() module which closes the Mozilla browser session on which the test will be executing.

@After

public void LogoutGmail() throws Exception {
driver.quit();
}

When you are done making the above changes your final code should look like this:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GmailLoginTest {
private Webdriver driver;
private final string GmailURL = “http://www.gmail.com”;

@Before

public void setUp() throws Exception() {
driver = new FirefoxDriver();
driver.get(GmailURL);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
}

@Test

public void LoginGmail() throws Exception {
driver.swtichTo().defaultContent();
WebElement userName = driver.findElement(By.id(“Email”);
userName.sendKeys(“youremail@gmail.com”);
WebElement password = driver.findElement(By.id(“Passwd”);
password.sendKeys(“yourPassword”);
driver.findElement(By.id(“signIn”).click();
}

@After

public void LogoutGmail() throws Exception {
driver.quit();
}

You can now execute the above script in the same way as you execute you java code and verify the results from all the assertions. However one capability which you lose in doing so is generating the well formatted reports in Selenium or Web driver.

After your script is edited you would be required to generate reports. For report generation you can take many approaches right from creating your own reporting module in java to using free open source tools which integrate well with this framework. The most talked about reporting tools are Ant and TestNg which can be easily setup if you have eclipse IDE. Although they make reporting pretty easy for someone who is creating a test script it does not capture all of the test scripts issues.

The other way to go is to create your own custom reports. For that you need to have hands-on with Java’s error handling utility. In our case for the Gmail login page we can put the part of logging in into a try catch block which will look to catch any exception during the logging in phase. In case there are no exceptions caught during the logging in process you can gather results from assertions at the end of the code which will determine if the Gmail page is loaded properly after login.

You can do that by looking for a particular element on the page if it is loaded or not by adding it in assertion module. All you have to do is to keep writing your results to a file of your favoured format from Assertions and Catch blocks.  (We prefer csv and HTML reports. Easy to generate and read)

More details on reporting would be covered in the next blog. Happy Coding !!

facebooktwittergoogle_plusredditlinkedinby feather

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>