26
Selenium Java Framework Last updated: 10 July 2017 © Pepgo Limited, 71-75 Shelton Street, Covent Garden, London, WC2H 9JQ, United Kingdom

Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

  • Upload
    lyminh

  • View
    261

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Selenium Java Framework

Last updated: 10 July 2017

© Pepgo Limited, 71-75 Shelton Street, Covent Garden, London, WC2H 9JQ, United Kingdom

Page 2: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Contents Introduction ............................................................................................................................................ 3

About this document .............................................................................................................................. 3

Naming conventions ............................................................................................................................... 3

JUnit Unit Testing in Java ........................................................................................................................ 4

JUnit Annotations................................................................................................................................ 4

JUnit Assert statements ...................................................................................................................... 4

Create a JUnit test suite ...................................................................................................................... 5

Run a JUnit test outside Eclipse .......................................................................................................... 6

How to build a JUnit Test - Example (in Eclipse): ................................................................................ 6

Example of a parameterised test ........................................................................................................ 8

EasyTest ................................................................................................................................................ 10

Data input and output ...................................................................................................................... 10

@Report annotation ......................................................................................................................... 10

Additional Maven settings for Linux ................................................................................................. 11

EasyTest Example .............................................................................................................................. 12

Installing and using Eclipse IDE with Maven ......................................................................................... 14

Install Java first .................................................................................................................................. 14

Install Eclipse IDE .............................................................................................................................. 14

Disable logging .................................................................................................................................. 19

A practical Selenium test example ........................................................................................................ 21

A Page Object example ......................................................................................................................... 23

Helper library ........................................................................................................................................ 26

Highlight an Element (highlightElement) .......................................................................................... 26

Verify Text Presence in page (isTextPresent) ................................................................................... 26

If Click is not working – use JavaScript (javascriptClick) ................................................................... 26

Page 3: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Introduction This framework for using Selenium with Java is based on the JUnit framework, which is the most

widely used framework for Unit Testing under Java. Many Java developers will already be familiar

with JUnit and use it for their Unit tests.

The JUnit framework is extended with EasyTest, which provides an easy open source data driven

testing framework. It allows for data driven tests from a variety of input and output data sources

(Microsoft Excel workbooks, CSV files, XML, and others), as well as basic reporting capabilities in

multiple formats (Adobe PDF, Microsoft Excel, HTML).

This framework also recommends the use of the Page Object pattern. The Page Object pattern

represents web pages as classes with custom-made methods for interactions with the page. This

makes tests more intuitively readable and also reduces the amount of duplicated code. If the User

Interface changes, the fix needs to be applied in one place only.

This framework also recommends to build a function library for general functions (a “Helper” class),

as well as adding one or multiple application specific libraries.

About this document This document gives a brief introduction to the framework and recommended Naming Conventions,

before it explains the use of JUnit with EasyTest.

It continues to describe the installation of the Eclipse IDE with Maven as build manager. Eclipse is

the Integrated Development Environment (IDE) of choice for this framework, although other IDE’s

can be used as well. This section also includes recommended Maven settings.

It then continues with samples for tests, Page Objects, and a generic Helper library:

A sample test that should be used as a template for any tests built with this framework.

A Page Object sample that should be used as a template for Page Objects used in this

framework.

A multi-purpose library that should be included (and extended over time) in all projects.

Naming conventions Class names start with an upper case letter.

Method names start with a lower case letter.

Variables start with a 3 digit lower case prefix that indicates the type of the variable, such as

“str” for “String”, “int” for “Integer”, “boo” for “Boolean” etc.

Literal names are all upper case letters (and additional characters if needed).

Page Object class names start with a prefix “PageObject_”.

Policy class names start with a prefix “Policy_”.

Page 4: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

JUnit Unit Testing in Java Typically unit tests are created in their own project or their own source folder to avoid that the

normal code and the test code is mixed.

JUnit is a test framework which uses annotations to identify methods that specify a test. Typically

these test methods are contained in a class which is only used for testing. It is typically called a Test

Class.

JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not

depend on other tests.

To write a test with JUnit you annotate a method with the “@org.junit.Test” annotation and

use a method provided by JUnit to check the expected result of the code execution versus the actual

result.

JUnit Annotations Annotation Description @Test public void

method()

The annotation @Test identifies that a method is a test method.

@Before public void

method()

This method is executed before each test. This method can prepare the test environment (e.g. read input data, initialize the class).

@After public void

method()

This method is executed after each test. This method can clean up the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.

@BeforeClass public

static void method()

This method is executed once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit.

@AfterClass public

static void method()

This method is executed once, after all tests have been finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.

@Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.

@Test (expected =

Exception.class)

Fails, if the method does not throw the named exception.

@Test(timeout=100) Fails, if the method takes longer than 100 milliseconds.

JUnit Assert statements JUnit provides static methods in the “Assert” class to test for certain conditions. These methods

typically start with “asserts” and allow you to specify the error message, the expected and the

Page 5: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

actual result. The following table gives an overview of these methods. Parameters in [] brackets are

optional.

Statement Description fail(String) Let the method fail. Might be used to check that a certain part

of the code is not reached. Or to have a failing test before the test code is implemented.

assertTrue([message],

boolean condition)

Checks that the boolean condition is true.

assertsEquals([String

message], expected,

actual)

Tests that two values are the same. Note: for arrays the reference is checked, not the content of the arrays.

assertsEquals([String

message], expected,

actual, tolerance)

Test that float or double values match. The tolerance is the number of decimals which must be the same.

assertNull([message],

object)

Checks that the object is null.

assertNotNull([message],

object)

Checks that the object is not null.

assertSame([String],

expected, actual)

Checks that both variables refer to the same object.

assertNotSame([String],

expected, actual)

Checks that both variables refer to different objects.

Create a JUnit test suite If you have several test classes you can combine them into a test suite. Running a test suite will

execute all test classes in that suite.

The following example code shows a test suite which defines that two test classes should be

executed. If you want to add another test class you can add it to “@Suite.SuiteClasses”

statement.

package com.pepgo.selenium;

import org.junit.runner.RunWith;

import org.junit.runners.Suite;

import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)

@SuiteClasses({ MyFirstTest.class, MySecondTest.class })

public class TestSuiteRunner {

@BeforeClass

public static void setup() {

// Only runs at the start

}

@AfterClass

public static void tearDown() {

// Only runs at the end

}

}

Page 6: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Run a JUnit test outside Eclipse Eclipse provides support for running your test interactively in the Eclipse IDE. You can also run your

JUnit tests outside Eclipse via standard Java code. The “org.junit.runner.JUnitCore” class

provides the “runClasses()” method, which allows you to run one or several tests classes. As a

return parameter you receive an object of the type “org.junit.runner.Result”. This object

can be used to retrieve information about the tests.

The following example class “JUnitTestRunner” will execute your test class and write potential

failures to the console.

package com.pepgo.selenium;

import org.junit.runner.JUnitCore;

import org.junit.runner.Result;

import org.junit.runner.notification.Failure;

public class JUnitTestRunner {

public static void main(String[] args) {

try {

Result result = JUnitCore.runClasses(JUnitTest.class);

for (Failure failure : result.getFailures()) {

System.out.println(failure.toString());

}

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

How to build a JUnit Test - Example (in Eclipse): 1. Create the following class in a new project:

package com.pepgo.selenium;

public class JUnitExample {

public int multiply (int x, int y) {

// the following is just an example

if (x > 999) {

throw new IllegalArgumentException("X must be less than 1000");

}

return x / y;

}

}

2. Right-click on the new class in the Package Explorer view and select “New” -> “JUnit Test

Case”. This will create a new JUnit test class. Set the name and the location of the test class,

Page 7: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

and click “Next” to select the methods that need to be covered by the test:

3. Create the JUnit test with the following code:

package com.pepgo.selenium;

import static org.junit.Assert.assertEquals;

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

public class JUnitExampleTest {

@BeforeClass

public static void testSetup() {

}

@AfterClass

public static void testCleanup() {

// Teardown for data used by the unit tests

}

@Test(expected = IllegalArgumentException.class)

public void testExceptionIsThrown() {

JUnitExample tester = new JUnitExample();

tester.multiply(1000, 5);

}

@Test

public void testMultiply() {

Page 8: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

try {

JUnitExample tester = new JUnitExample();

assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

4. Right-click on your new test class and select “Run-As” -> “JUnit Test”. The result will show

one successful test and one failed test. The red bar indicates that at least one test failed.

5. One test failed because the method “multiply” (created in step 1) divides instead of

multiplies. Change it from dividing to multiplying and run the test again. This time, it should

show to successful test results:

Note: Eclipse provides the shortcut Alt+Shift+X,T to run the test in the selected class. If you position

the cursor on one method name, this shortcut runs only the selected test method. Another way to

execute just one method is by right-clicking on the method in the JUnit view and selecting “Run”.

Example of a parameterised test JUnit allows you to use parameters in a tests class. This class can contain one test method and this

method is executed with the different parameters provided.

You mark a test class as a parameterized test with the “@RunWith(Parameterized.class)”

annotation.

Such a test class must contain a static method annotated with “@Parameters” that generates and

returns a Collection of Arrays. Each item in this collection is used as the parameters for the test

method.

Page 9: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

You need also to create a constructor in which you store the values for each test. The number of

elements in each array provided by the method annotated with “@Parameters” must correspond

to the number of parameters in the constructor of the class. The class is created for each parameter

and the test values are passed via the constructor to the class.

The following example code runs the previous test with 3 iterations of data. Only one single

parameter (“testParameter”) is used.

package com.pepgo.selenium;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import java.util.Collection;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.junit.runners.Parameterized;

import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)

public class JUnitParameterizedTest {

private int multiplier;

public JUnitParameterizedTest(int testParameter) {

try {

this.multiplier = testParameter;

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

// Creates the test data

@Parameters

public static Collection<Object[]> data() {

Object[][] data = new Object[][] { { 1 }, { 5 }, { 121 } };

return Arrays.asList(data);

}

@Test

public void testMultiplyException() {

try {

JUnitExample tester = new JUnitExample();

assertEquals("Result", multiplier * multiplier,

tester.multiply(multiplier, multiplier));

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

Page 10: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Executing this test in Eclipse will produce the following result:

EasyTest EasyTest is an open-source data driven testing framework based on the JUnit framework. EasyTest

imports and exports test data from a variety of formats (Microsoft Excel, CSV text files, XML sources,

and other data formats). EasyTest also has basic reporting capabilities to Adobe PDF format,

Microsoft Excel, and HTML format.

Data input and output EasyTest imports data per method. The first column in each (Microsoft Excel or CSV) input data file is

therefore reserved for the name of the method that the data will be used with, for example for the

method “getExcelTestData”:

getExcelTestData itemId libraryId

11567 91475

null 0

EasyTest saves any data that the test method returns into the same file as was used by the test class

to load the test data for that method. The data gets saved under the heading "ActualResult".

@Report annotation Reports can be generated by adding the “@Report” annotation at class level, for example:

@Report(outputFormats={Report.EXPORT_FORMAT.PDF, Report.EXPORT_FORMAT.XLS},

reportTypes={Report.REPORT_TYPE.DEFAULT, Report.REPORT_TYPE.METHOD_DURATION},

outputLocation="classpath:org/easetech/easytest/reports")

Alternatively, the report generation can also be driven through command line parameters.

Output formats are: PDF, HTML, XLS (optional, default is PDF).

Report types are: DEFAULT, METHOD_DURATION (optional, default is default).

Page 11: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

DEFAULT report is the original report that EasyTest generates. This report gives an overview of how

many tests were executed per class, which input and output parameters that the tests used, what

tests failed and what tests passed etc.

METHOD_DURATION report is more detailed and captures the maximum, minimum, and average

duration a test method took to execute and how many time a given test method was executed. The

report is depicted as a bar graph with a table that lists the average, minimum, and maximum time a

test method took.

Output location: For exporting to a classpath use: “classpath:”, for exporting to a disk location

use: “file:” (e.g. “file:c:\\reporting”) (optional, default is local location).

Additional Maven settings for Linux EasyTest reports use Microsoft fonts by default. This might be an issue on some Linux distributions

(such as Ubuntu). The following Maven settings must be added in Linux:

<repositories>

<repository>

<id>fdvsolution.public</id>

<url>http://archiva.fdvs.com.ar/repository/public1/</url>

</repository>

</repositories>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>4.3.9.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-beans</artifactId>

<version>4.3.9.RELEASE</version>

</dependency>

<dependency>

<groupId>ar.com.fdvs</groupId>

<artifactId>DynamicJasper-core-fonts</artifactId>

<version>1.0</version>

</dependency>

Page 12: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

EasyTest Example The following test gets its settings from a separate policy class and the data from a Microsoft Excel

workbook.

1. Test class:

package com.pepgo.selenium;

import org.easetech.easytest.annotation.*;

import org.easetech.easytest.runner.DataDrivenTestRunner;

import org.junit.Assert;

import org.junit.Test;

import org.junit.runner.RunWith;

@RunWith(DataDrivenTestRunner.class)

@TestPolicy(Policy_TemperatureConverterSample.class)

public class TemperatureConverterSample {

@Test

public void testToCelsiusConverter(@Param(name = "fahrenheit") int intFahrenheit,

@Param(name = "celsius") int intCelsiusResult) {

try {

int intCelsius = (intFahrenheit - 32) * 5 / 9;

System.out.println(intFahrenheit + " Fahrenheit = " + intCelsius + "

Celsius");

// Assert the result from the business method with the celsius result

that comes from the input data file

Assert.assertEquals(intCelsiusResult, intCelsius);

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

2. Test policy class (for running 5 threads in parallel):

package com.pepgo.selenium;

import org.easetech.easytest.annotation.*;

@DataLoader(filePaths = { "C:\\Selenium\\temperatureConversionData.xls" })

@Format(date="dd/MM/yyyy")

@Report(outputFormats={Report.EXPORT_FORMAT.PDF}, reportTypes={Report.REPORT_TYPE.DEFAULT},

outputLocation="file:C:\\Temp")

@Parallel(threads=5)

public class Policy_TemperatureConverterSample {

}

3. The Microsoft Excel data file (Sheet1 of the file “temperatureConversionData.xls”):

Page 13: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

testToCelsiusConverter fahrenheit celsius

0 -17

1 -17

2 -16

3 -16

4 -15

5 -15

6 -14

7 -13

8 -13

9 -12

An extract from a sample Adobe PDF report generated by EasyTest:

Page 14: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Installing and using Eclipse IDE with Maven This section describes the installation and use of the Eclipse IDE (Integrated Development

Environment) with Maven. It is of course also possible to use other Java IDE’s.

Install Java first On Microsoft Windows, it is required to install Java first as a perquisite to installing the Eclipse IDE. It

is recommended to install the latest stable Oracle Java Development Kit (JDK). The Java Standard

Edition (SE) should be sufficient, as the Java Enterprise Edition (EE) is usually only required for very

large scale (Enterprise) projects.

Many Linux distributions already include Java OpenJDK, the open-source implementation of the Java

SE Platform. OpenJDK is almost entirely identical to Oracle Java and can be used as an alternative to

Oracle Java. OpenJDK was established as an open-source alternative to Oracle Java, after Oracle Java

became proprietary software. OpenJDK aims to provide the same functionality as Oracle Java.

Install Eclipse IDE The recommended version of the Eclipse IDE is "Eclipse IDE for Java Developers", which can be

downloaded from http://www.eclipse.org/downloads .

Once installed, a new Selenium project can be built:

1. Launch the Eclipse IDE.

2. Create a new project by selecting “File” -> “New” -> “Other” from the Eclipse main menu.

Page 15: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

3. On the “New” dialog, select “Maven” -> “Maven Project”:

4. Next, in the “New Maven Project” dialog box; check the “Create a simple project (skip

archetype selection)” checkbox and keep everything as default and click on the “Next”

button:

Page 16: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

5. On the New Maven Project dialog box, enter your project name (in this example

“com.pepgo.selenium”) in the “Group Id:” and “Artifact Id:” textboxes. You can also add a

name and description. Keep everything else as default and click on the “Finish” button:

6. The project creation might take several minutes. Eclipse will create your project (in this

example “com.pepgo.selenium”) with a folder structure (in Package Explorer):

On a fresh installation of Eclipse, it is likely that you will get a warning message that your

built path points to a wrong execution environment. If you have this problem, then you can

fix it with the following 7 steps:

1. Right-click on you project (in the Package Explorer) and select “Properties”.

2. Click on the “Libraries” tab.

3. Select the old library (for example "JRE System Library[J2SE 1.5]" and click on “Remove”.

4. Click on “Add Library”.

5. Click on “JRE System Library” and “Next”.

6. Select the new "Execution Environment" or “Workspace default JRE”. If you have just

installed the Java JDK, then you will most likely want to just leave the selection “Workspace

Page 17: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

default JRE”:

7. Add a package of the same name as the project (for example “com.pepgo.selenium”) under

the folder where you like to create your test classes (either “…/src/main/java” or

“…/src/test/java”), for example:

8. Select “pom.xml” from Package Explorer. This will open the (Maven) “pom.xml” file in the

editor area with the Overview tab open. Select the “pom.xml” tab instead.

9. Replace the “pom.xml” settings with the following settings and save everything (“File” ->

“Save all”.

<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.pepgo.selenium</groupId>

<artifactId>com.pepgo.selenium</artifactId>

<packaging>jar</packaging>

<version>1.0-SNAPSHOT</version>

<dependencies>

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>3.4.0</version>

</dependency>

Page 18: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

</dependency>

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>1.7.25</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-log4j12</artifactId>

<version>1.7.25</version>

</dependency>

<dependency>

<groupId>org.easetech</groupId>

<artifactId>easytest-core</artifactId>

<version>1.4.0</version>

</dependency>

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.16</version>

</dependency>

<dependency>

<groupId>xml-apis</groupId>

<artifactId>xml-apis</artifactId>

<version>2.0.2</version>

</dependency>

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>3.16</version>

<exclusions>

<exclusion>

<artifactId>xml-apis</artifactId>

<groupId>xml-apis</groupId>

</exclusion>

</exclusions>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-shade-plugin</artifactId>

<version>3.0.0</version>

<executions>

<execution>

<phase>package</phase>

<goals>

<goal>shade</goal>

</goals>

</execution>

</executions>

<configuration>

<filters>

<filter>

<artifact>*:*</artifact>

<excludes>

Page 19: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

<exclude>META-INF/*.SF</exclude>

<exclude>META-INF/*.DSA</exclude>

<exclude>META-INF/*.RSA</exclude>

</excludes>

</filter>

</filters>

<finalName>uber-${project.artifactId}-${project.version}</finalName>

</configuration>

</plugin>

</plugins>

</build>

</project>

This “pom.xml” is a template that can and should be customised to individual requirements. It

needs to be updated constantly with the latest version number for all artifacts. The latest settings

for all artifacts can be queried from http://mvnrepository.com/ .

Artifact Required Used for selenium-java Yes Selenium functionality junit Yes JUnit unit testing framework log4j Yes Logging framework slf4j Yes Logging (simple facade for log4j) easytest-core Yes EasyTest framework poi No (optional) Apache POI is used for reading and writing Microsoft

Excel files. It is often used in Selenium tests. xml-apis No (optional) XML handling, used for Apache POI maven-shade-plugin No (optional) This plugin provides the capability to package all

artifacts in an uber-jar, which means that all jars will be packed into one giant jar that contains all Maven referenced artifacts. Having just one giant jar makes it much easier to deploy, as only a single file needs to be deployed. However, any project classes created and libraries added outside of Maven (for example Microsoft JDBC drivers) must be added manually to the uber-jar. This plugin makes up the whole <build> section. From experience, the Maven shade plugin often fails to create valid Java manifest files, which is why this template includes <excludes> settings.

Disable logging To switch off (log4j) logging, the following “log4j.xml” file needs to be placed in the desired

target path (“classes” or “test-classes”), for example in

“…\workspace\com.pepgo.selenium\target\classes”:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration threshold="off">

<appender name="console" class="org.apache.log4j.ConsoleAppender">

<param name="Threshold" value="off" />

</appender>

<appender name="rolling-file" class="org.apache.log4j.ConsoleAppender">

Page 20: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

<param name="Threshold" value="off" />

</appender>

</log4j:configuration>

Page 21: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

A practical Selenium test example This tests uses Google Chrome to collect the current time and date of the world’s biggest 10

metropolitan areas. The input data comes from a Microsoft Excel workbook.

1. Test class:

package com.pepgo.selenium;

import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.easetech.easytest.annotation.*;

import org.easetech.easytest.runner.DataDrivenTestRunner;

import org.junit.Assert;

import org.junit.BeforeClass;

import org.junit.Test;

import org.junit.AfterClass;

import org.junit.runner.RunWith;

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;

@RunWith(DataDrivenTestRunner.class)

@TestPolicy(Policy_WorldCityTimeSample.class)

public class WorldCityTimeSample {

private static WebDriver driver;

private WebElement elem;

private String strCityUrl, strTime, strDate;

private static StringBuffer verificationErrors = new StringBuffer();

@BeforeClass

public static void setUp() {

try {

System.setProperty("webdriver.chrome.driver",

"C:\\Selenium\\chromedriver.exe");

driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

@Test

public void queryWorldCityTime(@Param(name = "city") String strCity) {

try {

// Replace possible spaces in city names with %20 (for URL)

strCityUrl = strCity.replace(" ", "%20");

// Get web page

driver.get("https://www.google.com/search?q=time%20" + strCityUrl);

// Read time as string

elem = driver.findElement(By.xpath("//div[@class='vk_bk vk_ans']"));

strTime = elem.getText();

// Read date as string

elem = driver.findElement(By.xpath("//div[@class='vk_gy vk_sh']"));

strDate = elem.getText();

// Write message to console

System.out.println("The time in " + strCity + " is " + strTime + " on "

+ strDate + ".");

// Assert that time been retrieved

Assert.assertNotEquals(strTime.length(), 0);

// Assert that date been retrieved

Assert.assertNotEquals(strDate.length(), 0);

Page 22: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

// Wait 3 seconds to avoid Google captchas

Thread.sleep(3000);

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

@AfterClass

public static void tearDown() {

try {

driver.quit();

String verificationErrorString = verificationErrors.toString();

if (!"".equals(verificationErrorString))

{

fail(verificationErrorString);

}

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

2. Test Policy class:

package com.pepgo.selenium;

import org.easetech.easytest.annotation.DataLoader;

import org.easetech.easytest.annotation.Format;

import org.easetech.easytest.annotation.Report;

@DataLoader(filePaths = { "C:\\Selenium\\queryWorldCityTime.xls" })

@Format(date="dd/MM/yyyy")

@Report(outputFormats={Report.EXPORT_FORMAT.PDF}, reportTypes={Report.REPORT_TYPE.DEFAULT},

outputLocation="file:C:\\Temp")

public class Policy_WorldCityTimeSample {

}

3. The Microsoft Excel data file (sheet1 of the workbook “temperatureConversionData.xls”):

queryWorldCityTime City

Tokyo

Jakarta

Seoul

Delhi

Shanghai

Manila

Karachi

New York

Sao Paulo

Mexico City

Page 23: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

A Page Object example This example uses a Selenium Page Object to retrieve Google search pages for the keywords

“London”, “Paris” and “New York”. It uses standard JUnit functionality without EasyTest.

It is good practise in Selenium to collect actions on a page into a Page Object. The resulting methods

allow the abstraction from the underlying Selenium program code and increase the readability and

maintainability of the tests, particularly in large test suites.

Calling test class:

package com.pepgo.selenium;

import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.BeforeClass;

import org.junit.Test;

import org.junit.AfterClass;

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;

public class GoogleSearchSample {

private static WebDriver driver;

private static StringBuffer verificationErrors = new StringBuffer();

@BeforeClass

public static void setUp() {

try {

System.setProperty("webdriver.chrome.driver",

"C:\\Selenium\\chromedriver.exe");

driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

@Test

public void searchForUsingPageObject() {

try {

// Initialise the page object

PageObject_GoogleSearchSample pageOne = new

PageObject_GoogleSearchSample(driver).get();

// Use the page object

pageOne.searchFor("London");

pageOne.searchFor("Paris");

pageOne.searchFor("New York");

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

@AfterClass

public static void tearDown() {

try {

driver.quit();

Page 24: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

String strVerificationErrorString = verificationErrors.toString();

if (!"".equals(strVerificationErrorString))

{

fail(strVerificationErrorString);

}

}

catch(Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

Page Object class:

package com.pepgo.selenium;

import org.junit.Assert;

import org.openqa.selenium.support.FindBy;

import org.openqa.selenium.support.How;

import org.openqa.selenium.support.PageFactory;

import org.openqa.selenium.support.ui.LoadableComponent;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

public class PageObject_GoogleSearchSample extends

LoadableComponent<PageObject_GoogleSearchSample> {

private WebDriver driver;

// This element is looked up using the name attribute

@FindBy(how = How.NAME, using = "q")

private WebElement googleSearchBox;

// This element is looked up using the ID attribute

@FindBy(how = How.ID, using = "gbqfba")

private WebElement googleSearchButton;

// Constructor

public PageObject_GoogleSearchSample(WebDriver driver) throws Exception {

this.driver = driver;

// This call sets the WebElement fields

PageFactory.initElements(driver, this);

}

// ATTENTION: The load() method is only called AFTER the isloaded() method!

@Override

protected void load() {

driver.get("https://www.google.com/");

}

@Override

protected void isLoaded() throws Error {

this.load();

Assert.assertEquals("Google", driver.getTitle());

}

// Custom method

public void searchFor(String searchTerm) throws Exception {

// Continue using the element just as before

googleSearchBox.clear();

googleSearchBox.sendKeys(searchTerm);

googleSearchButton.submit();

Page 25: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

// Display the page for 5 seconds (just for visual confirmation, not necessary

as program code)

try {

Thread.sleep(5000);

}

catch (InterruptedException e) {

e.printStackTrace();

}

// Reset the application to the initial state by calling the load() method

again

this.load();

}

}

Page 26: Selenium Java Framework - Automated software testing · Selenium Java Framework Last ... This document gives a brief introduction to the framework and recommended Naming ... the Integrated

Helper library The helper library is class with “static” type of behaviour that provides general purpose functions.

These functions can therefore be called from tests using the syntax:

Helper.functionname(Parmeters…)

Highlight an Element (highlightElement) While debugging, sometimes it is very helpful if the element you are going to interact with can be

highlighted. The function will create a border around the element.

Verify Text Presence in page (isTextPresent) This function returns true if a text is shown on a page and false if it isen’t.

If Click is not working – use JavaScript (javascriptClick) There may be times when the click API provided by WebDriver is not working, or it is not returning the

control. You can use JavaScript to click on the element at this time.

package com.pepgo.selenium;

import org.openqa.selenium.*;

public class Helper {

// Use a private constructor to make the class "static"

private Helper(){}

// Highlight an element on a web page

public static void highlightElement(WebDriver driver, WebElement element) throws

Exception {

((JavascriptExecutor)

driver).executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element,

"style", "border: 2px solid yellow; color: yellow; font-weight: bold;");

}

// Check if a text is displayed on a web page

public static boolean isTextPresent(WebDriver driver, String strText) throws Exception

{

if (driver.getPageSource().contains(strText))

return true;

else

return false;

}

// Click using JavaScript

public static void javascriptClick(WebDriver driver, WebElement element) throws

Exception {

((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);

}

}