Setup Eclipse for Automation Testing

Update

This article is still relevant but a more comprehensive guide exists at http://timothycope.com/c-selenium-automation. This new guide also covers Page Object Design Pattern (POM) and Selenium Server (Grid).

Background

Eclipse is an IDE for many languages and in this case we will use it for Java development. Tests created using Selenium IDE can be exported to Java and ran in Eclipse using the JUnit plugin.

Getting What you Need

Eclipse will be an executable while jUnit and Selenium will be .jar files.

  1. Eclipse (for Java Developers) – http://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/mars1
  2. JUnit – https://github.com/junit-team/junit/wiki/Download-and-Install 
  3. Selenium (Server and Client) – http://www.seleniumhq.org/download/
  4. Selenium IDE – http://www.seleniumhq.org/download/

Setting It All Up

  1. Install Eclipse
    1. For OSX, when the .tar.gz file opens move the extracted app to your Applications folder.
  2. Run Eclipse
    1. For OSX, open your Applications folder and then right-click Eclipse and select Open. Select Open from the prompt.
  3. For now, just use the default workspace. So, simply select Ok when the workspace prompt appears
  4. Close the welcome screen by clicking the X on its tab
    1. You should now see a blank project explorer
  5. From the menu select File -> New -> Java Project
  6. Name the project “Example” and select Finish
  7. Right-click in the Package Explorer pane and select New -> Folder
  8. Select “Example” as the parent folder
  9. Name the new folder “lib” and select Finish
    1. This will act as our “libraries” folder
  10. Copy over the .jar files to the “lib” folder (you can drag and drop)
    1. junit-#.#.jar
    2. selenium-server-standalone-#.#.#.jar
    3. selenium-java-#.#.#.jar
  11. Select Copy files on the prompt
  12. Select all files in the lib folder, right-click and select Build Path -> Add to Build Path
    1. This will copy the files into a folder called “Referenced Libraries” in your Package Explorer

Creating an Example Test Using Selenium IDE

  1. Install Selenium IDE if you haven’t already
    1. Use Firefox to download using the link on the Selenium downloads page
  2. Open Firefox
  3. Click the Selenium icon to the right of the address bar
  4. Enter https://www.google.com as your Base URL
  5. Click the record button (if not already recording)
    1. Navigate to https://www.google.com/
    2. Type Tim
    3. Click Search button
    4. Right-click on the page and select waitForTitle Tim – Google Search from the context menu
    5. Click the record button to stop recording
  6. Click the Play Current Test button
    • Ensure all steps are highlighted in green, meaning the test passed
  7. Click File -> Export Test Case As… and select Java/JUnit4/Webdriver
  8. Save as “test01.java

Adding the Test to the Eclipse Project

  1. Add/Drag-and-drop the .java file into the “src” folder of your project
    1. Select Copy file if prompted
  2. There will be errors reported during the import so let’s fix those:
    1. In the Package Explorer, drill down to the newly added test and double-click it
      1. Example -> src -> default package -> test01.java
    2.  The declared package “com.example.tests” does not match the expected package “” test01.java /Example/src line 1 Java Problem
      1. Remove the line “package com.example.tests;”
    3. The public type Test01 must be defined in its own file test01.java /Example/src line 12 Java Problem
      1. Rename the class “test01”
    4. Save the changes and refresh the package explorer (F5)

Running Your First Test

  1. Right-click the test in the package explorer and select Run As -> JUnit Test
  2. Eclipse will open the JUnit pane and execute the test in Firefox (the default WebDriver).
  3. Upon completion you should see the result(s)

Running More Tests

You can add more test to the default package. When you want to run them all you can select the default package folder and run as a JUnit test.

Running Tests Using a Headless Browser

A headless browser is an “internet browser” without a GUI. For this example, we will use HtmlUnit. It is an HtmlClient wrapper for Java applications. Get it here, http://sourceforge.net/projects/htmlunit/files/htmlunit/.

  1. Download the .jar file
  2. Add the .jar file to your “lib” folder
  3. Add the file to your build path
  4. Using the test created (above):
    1. Using //, comment out the line private WebDriver driver;
    2. Add a line under that, private HtmlUnitDriver driver;
      1. Hover over WebClient and select Import ‘HtmlUnitDriver’ (org.openqa.selenium.htmlunit)
      2. This will add the reference for WebClient from the HtmlUnit jar
    3. Using //, comment out the line driver = new FirefoxDriver();
    4. Add a line under that, driver = new HtmlUnitDriver();
    5. Add a line under that, driver.setJavascriptEnabled(true);
  5. Save your changes
  6. Execute the test
    1. Note: HtmlUnit will show a bunch of warnings, ignore them for now as it is normal behavior
      1. These warnings related to the page being loaded (akin to DevTools Console) and not the test itself
    2. Note: Google changes IDs based on browsers so this example will fail since it was recorded in Firefox and will be ran using HtmlUnit [Source].
      1. You can set the User-Agent by setting, driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_38);
      2. You will also have to hover over BrowserVerison and add the missing reference, Import ‘BrowserVersion’ (com.gargoylesoftware.htmlunit)
      3. Documentation on BrowserVersion

Using HtmlUnit to Scrape Webpages

Background

HtmlUnit is a “GUI-Less browser for Java programs”. It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc… just like you do in your “normal” browser.
http://htmlunit.sourceforge.net/

Problem

We want to use a headless browser’s functions to scrape a webpage for all instances of <a> to verify each contains a title="" attribute. This will be an accessibility test.

Environment

I am using OSX, Eclipse for Java, and JUnit but everything I cover can be applied to whatever environment you develop in. My environment is the one setup in a previous post, http://timothycope.com/?p=274

Solution- Using HtmlUnit to Scrape Webpages

We’ll need to import HtmlUnit’s .jar file into the Eclipse project. After that’s done we can create an instance of HtmlUnit, called a WebClient.

import java.util.List;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class AccessibilityTest
{
	public static void CheckSelections()
	{
		// Run test
		CheckAnchorTitle();
	}

	private static void CheckAnchorTitle()
	{
		// Create a WebClient using HtmlUnit (a headless browser)
		WebClient webClient = new WebClient();

		// Create a new StringBuilder() for the log
		StringBuilder sb = new StringBuilder();
		sb.append("Check Anchor Title - Results:");

		try
		{
			// Get the HtmlPage
			HtmlPage page = webClient.getPage(AutoMater.url_SiteToTest);

			// Extract every <a> instance
			final List<DomElement> anchorList = page.getElementsByTagName("a");

			// For each <a> in anchorList
			for( int i = 0; i < anchorList.size(); i++ )
			{
				// Get the current <a>
				HtmlAnchor anchor = (HtmlAnchor) anchorList.get(i);

				// See if the title='' attribute is present with the <a>
				if ( anchor.getAttribute("title").isEmpty() )
				{
					// Write exception to string builder
					sb.append(System.getProperty("line.separator"));
					sb.append("Missing Title: " + anchor);
				}
			}
		}
		catch (Exception ex)
		{
			// Write exception to string builder
			sb.append(System.getProperty("line.separator"));
			sb.append("Exception: " + ex);
		}
		finally
		{
			// Close the web client
	 		webClient.closeAllWindows();

	 		// Add the test execution information to the end of the log
	 		sb.append(TestTimer.Result());

	 		// Write the results to the log
			System.out.print(sb.toString());
		}
	}
}

Handling Pop-ups with Selenium IDE and Java

Problem – Selenium Popup

You need to test an anchor whose target is _blank.

Example

http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html

<a href="newwindow.html" target="_blank">a new window</a>

Solution in IDE

  1. Open Firefox
  2. Click the Selenium icon to the right of the address bar
  3. Enter http://www.htmlcodetutorial.com/ as your Base URL
  4. Click the record button
    1. Navigate to http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html
    2. Left-click the a new window link
    3. Right-click on the page and select verifyTitle A Whole New Window – HTML Code Tutorial
    4. Close the new window/tab
    5. Right-click on the original window/tab page and select verifyTitle HTML _blank – HTML Code Tutorial
  5. In Selenium IDE, click the record button to stop recording
  6. Add a pause 1000 step after the click step to give the window/tab time to load
  7. Add a selectWindow A Whole New Window – HTML Code Tutorial step after the pause to connect to the new window/tab
  8. Add a close step after the verifyTitle A Whole New Window – HTML Code Tutorial step
  9. Add a selectWindow HTML _blank – HTML Code Tutorial step after the close step
  10. Select Play Current Test Case to verify the test

Your test should look like this:

Capture

Solution in Java

  1. Export the test from the IDE solution (above)
    • Click File -> Export Test Case As… and select Java/JUnit4/Webdriver
    • Save as test01.java in your project’s src folder
    • Refresh your project in Eclipse (F5)
    • Fix any errors in the code and save
      • Remove package com.example.tests;
  2.  Open Test01.java
    • Scroll down some and you will see some comments, like // ERROR: Caught exception [ERROR: Unsupported command [selectWindow | A Whole New Window – HTML Code Tutorial | ]]
    • Some of Selenium IDE’s functions don’t have WebDriver equivalents just yet
  3. Before the link click event add String parentHandle = driver.getWindowHandle();
    • This will get the parent window handle
  4. After the link click event add for (String winHandle : driver.getWindowHandles()) {driver.switchTo().window(winHandle);}
    • This will switch us to the child window
  5. After the close event add driver.switchTo().window(parentHandle);
    • This will switch us back to the parent window
  6. Right-click somewhere in the code file and select Run As -> JUnit Test
    • Or, click the green run button on the Eclipse toolbar
    • A browser window should open and run the test
    • The test results should display on the left pane of the Eclipse window

Your code for @test should look like:

@Test
public void test01() throws Exception {
	driver.get(baseUrl + "linking/_A_TARGET_95y98y108y97y110y107y.html");
	String parentHandle = driver.getWindowHandle();
	driver.findElement(By.linkText("a new window")).click();
	for (String winHandle : driver.getWindowHandles()) {
		driver.switchTo().window(winHandle);
	}
	try {
	  assertEquals("A Whole New Window - HTML Code Tutorial", driver.getTitle());
	} catch (Error e) {
	  verificationErrors.append(e.toString());
	}
	driver.close();
	driver.switchTo().window(parentHandle);
	try {
	  assertEquals("HTML _blank - HTML Code Tutorial", driver.getTitle());
	} catch (Error e) {
	  verificationErrors.append(e.toString());
	}
}

Setup Selenium, JUnit, and Eclipse

Update

This article is still relevant but a more comprehensive guide exists at http://timothycope.com/c-selenium-automation. This new guide also covers Page Object Design Pattern (POM) and Selenium Server (Grid).

Background

Selenium automates browsers. That’s it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.
http://docs.seleniumhq.org/

JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.
http://junit.org/

Eclipse is a platform that has been designed from the ground up for building integrated web and application development tooling. By design, the platform does not provide a great deal of end user functionality by itself. The value of the platform is what it encourages: rapid development of integrated features based on a plug-in model.
https://www.eclipse.org/

Setup Eclipse

  1. Go to https://github.com/junit-team/junit/wiki/Download-and-Install and download “junit.jar”
    • (Optional) You can also grab the “hamcrest-core.jar”
      • “junit.jar” contains common functions of hamcrest, which can be expanded by using the core library
  2. Go to http://www.seleniumhq.org/download/ and download “Selenium Server” and “Selenium Client”
    • We will be using the Java client, which comes in an archive. We are only concerned with the .jar not including “srcs” in the file name
  3. Go to https://www.eclipse.org/downloads/ and download the version you need for your operating system
    • I use Eclipse IDE for Java Developers
  4. Extract the archive
    • (Optional) Move the extracted folder to your application folder
  5. Run the executable for Eclipse
  6. Select a workspace
  7. Click File -> New -> Java Project
    • For standard IDE Find/Select Java Project
  8. Name your project and click Finish
    • The default settings are good for this tutorial
  9. Create a new folder called “lib” in your project to hold the external assemblies
    • The name does not matter, but should make sense
  10. Drag-and-Drop the .jar files for Selenium Server, Selenium Client, and JUnit into the new folder
    • When prompted, select Copy Files
  11. Expand the lib folder and select the .jar files
  12. Right-click and select Build Path -> Add to Build Path
    • This will create a new folder called “Referenced Libraries” that contains the binaries for the .jar files

Creating Your First Test

Until you become a Subject Matter Expert you will likely be using the Selenium IDE for Firefox to write your tests. You can download the IDE from http://www.seleniumhq.org/download/

  1. Open Firefox
  2. Click the Selenium icon to the right of the address bar
  3. Enter https://www.google.com/ as your Base URL
  4. Click the record button
    1. Navigate to https://www.google.com/
    2. Type Tim
    3. Click Search button
    4. Right-click on the page and select waitForTitle Tim – Google Search from the context menu
    5. Click the record button to stop recording
  5. Click the Play Current Test button
    • Ensure all steps are highlighted in green, meaning the test passed
  6. Click File -> Export Test Case As… and select Java/JUnit4/Webdriver
  7. Save as test01.java in your project’s src folder
  8. Refresh your project in Eclipse (F5)
  9. Fix any errors in the code and save
    • Remove package com.example.tests;
    • Rename public class Test01 to test01
  10. Right-click somewhere in the code file and select Run As -> JUnit Test
    • Or, click the green run button on the Eclipse toolbar
  11. A browser window should open and run the test
  12. The test results should display on the left pane of the Eclipse window