Testing automation with Selenium

Never send a human to do a machine’s job

Testing a CRM application which I am part of became very difficult over the recent months. There were simply too many usecases. Despite unit testing on the backend services (SOA), bugs crept in on a regular basis considering a lot of logic is on the javascript and other layers of the application.

This is Part 1 of this series explaining how the following problems that I faced during testing were addressed :

  • There were too many combinations of test scenarios
  • Application logic was spread over javascript, front-end, service and database tiers
  • Existing testcases for services/portals are not exhaustive
  • Our Unit testcases verified against static data
  • Enabling/disabling/visibility/invisibility of fields on the front end could not be verified by plain Unit tests
  • Incremental failure built inside JUnit testcases is not always useful. A report of all the issues would be nice.

The itch and the scratch

The Tool was built upon Selenium, Spring and Velocity.

Tool Stack

The following features were built into the tool

Problem vs Feature

Problem vs Feature

Selenium

As part of the web automation, a series of utility methods was written/stolen from various sources. I am sure you’ll find the SeleniumUtils class interesting and useful.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * @author Arun Manivannan
 *
 */
public class SeleniumUtils {

	private static Logger logger=Logger.getLogger(SeleniumUtils.class);

	public static void populateDropDown(WebDriver driver, By by, String value) {

		Select select = new Select(driver.findElement(by));
		select.selectByValue(value);

	}

	public static ExpectedCondition<WebElement> visibilityOfElementLocated(final By locator) {
		return new ExpectedCondition<WebElement>() {
			public WebElement apply(WebDriver driver) {
				WebElement toReturn = driver.findElement(locator);
				if (toReturn.isDisplayed()) {
					return toReturn;
				}
				return null;
			}
		};
	}

	public static void populateTextBox(WebDriver driver, By by, String value) {
		WebElement inputElement = driver.findElement(by);
		if ("".equals(value)) {
			inputElement.clear();
		} else {
			inputElement.sendKeys(value);
		}
	}

	public static void checkRadio(WebDriver driver, By by) {
		WebElement inputElement = driver.findElement(by);
		inputElement.click();
	}


	public static void goToTab(WebDriver driver, By by) {
		waitUntilClickable(driver, by);
		driver.findElement(by).click();
	}

	public static WebElement waitForVisibility(WebDriver driver, By by) {
		return waitForVisibility(driver, by, 45);
	}

	public static WebElement waitUntilClickable(WebDriver driver, By by){
		WebDriverWait wait = new WebDriverWait(driver, 45);
		WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by));
		return element;
	}

	public static WebElement waitForVisibility(WebDriver driver, By by, int waitTime) {
		Wait<WebDriver> wait = new WebDriverWait(driver, waitTime);
		WebElement divElement = wait.until(visibilityOfElementLocated(by));
		return divElement;
	}


	public static WebElement switchToNewWindow(WebDriver driver, String iframeId) {
		driver.switchTo().frame(iframeId);
		WebElement window = driver.switchTo().activeElement();
		return window;
	}

	public static String getTextFromId(WebDriver driver, WebElement navigator, String id) {

		//String text = navigator.findElement(By.id(id)).getText();
		System.out.print(id); 
		final WebElement element = findElement(driver, By.id(id),3);

		ElementType currentElementType=getCurrentElement(element);
		String text=StringUtils.EMPTY;
		switch (currentElementType) {
		case INPUT:
			text=element.getAttribute("value");
			break;
		case DIV:
			text=element.getText().trim();
			break;
		case TEXTAREA:
			//text=element.getText();
			text =  (String)((JavascriptExecutor) driver).executeScript("return document.getElementById('"+id+"').value","");
			break;
		case SELECT:
			//Select select=new Select(element);
			//text=select.getFirstSelectedOption().getAttribute("value");
			text =  (String)((JavascriptExecutor) driver).executeScript("return document.getElementById('"+id+"').value","");
			break;	
		default:
			break;
		}

		System.out.println(" : Text value : "+text);
		return text;

	}

	private static ElementType getCurrentElement(WebElement element) {
		String tagName=element.getTagName();
		ElementType elementType=null;
		if (StringUtils.equalsIgnoreCase(tagName, Constants.INPUT)){
			elementType=ElementType.INPUT;
		}
		else if (StringUtils.equalsIgnoreCase(tagName, Constants.SELECT)){
			elementType=ElementType.SELECT;
		} 
		else if (StringUtils.equalsIgnoreCase(tagName, Constants.DIV)){
			elementType=ElementType.DIV;
		} 
		else if (StringUtils.equalsIgnoreCase(tagName, Constants.TEXTAREA)){
			elementType=ElementType.TEXTAREA;
		} 
		else{
			logger.error("Unhandled element type : "+element.getTagName());
		}

		return elementType;
	}

	public static WebElement findElement(WebDriver driver, By by, int timeoutInSeconds){
	    try {
			WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
			wait.until(ExpectedConditions.presenceOfElementLocated(by));
		} catch (TimeoutException e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			return null;
		} 
	    return driver.findElement(by);
	}

	public static boolean isEnabled(WebDriver driver, String eachField) {
		return (driver.findElement(By.id(eachField)).isEnabled());
	}

	public static boolean isDisabled(WebDriver driver, String eachField) {
		return (!driver.findElement(By.id(eachField)).isEnabled());
	}

	public static boolean isVisible(WebDriver driver, String eachField) {
		return (driver.findElement(By.id(eachField)).isDisplayed());
	}

	public static boolean isInvisible(WebDriver driver, String eachField) {
		return (!driver.findElement(By.id(eachField)).isDisplayed());
	}


	public static  List<Message> checkEnabledFields(WebDriver driver, List<String> enabledFields) {
		System.out.println("Check enabled fields");
		if (enabledFields==null) return ListUtils.EMPTY_LIST;
		List<Message> messages=new ArrayList<Message>();
		boolean result=false;
		for (String eachField: enabledFields) {
			result=isEnabled(driver, eachField);
			messages.add(ValidationReportUtils.constructFieldValidationMessageFromResult(result, Constants.ENABLED, Constants.DISABLED, eachField));
		}
		return messages;
	}


	public static  List<Message> checkDisabledFields(WebDriver driver, List<String> fields) {
		if (fields==null) return ListUtils.EMPTY_LIST;
		List<Message> messages=new ArrayList<Message>();
		boolean result=false;
		for (String eachField: fields) {
			result=isDisabled(driver, eachField);
			messages.add(ValidationReportUtils.constructFieldValidationMessageFromResult(result, Constants.DISABLED, Constants.ENABLED, eachField));
		}
		return messages;

	}

	public static  List<Message> checkVisibleFields(WebDriver driver, List<String> fields) {
		if (fields==null) return ListUtils.EMPTY_LIST;
		List<Message> messages=new ArrayList<Message>();
		boolean result=false;
		for (String eachField: fields) {
			result=isVisible(driver, eachField);
			messages.add(ValidationReportUtils.constructFieldValidationMessageFromResult(result, Constants.VISIBLE, Constants.INVISIBLE, eachField));
		}
		return messages;

	}

	public static  List<Message> checkInvisibleFields(WebDriver driver, List<String> fields) {
		if (fields==null) return ListUtils.EMPTY_LIST;
		List<Message> messages=new ArrayList<Message>();
		boolean result=false;
		for (String eachField: fields) {
			result=isInvisible(driver, eachField);
			messages.add(ValidationReportUtils.constructFieldValidationMessageFromResult(result, Constants.INVISIBLE, Constants.VISIBLE, eachField));
		}
		return messages;

	}

	public static String captureScreenshot(WebDriver driver, String folder, String fileName) {

		File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		File targetFile=new File(folder, fileName+".png");
		try {
			FileUtils.copyFile(screenshotFile,targetFile );
		} catch (IOException e) {
			logger.error ("Error while writing file ",e);
		}

		return targetFile.getAbsolutePath();
	}
}