Calling the W3C Validator API Using Java

Background

The Markup Validator is a free service by W3C that helps check the validity of Web documents.
http://validator.w3.org/about.html

Markup Validator Web Service

Interface applications with the Markup Validator through its experimental API. This is version 0.2, dated May 2007. For a history of the format, see Change Log.
http://validator.w3.org/docs/api.html

To call this service you’ll need to make an HTTP request for http://validator.w3.org/check?output=soap12&uri= with your appended URL. The parameter output tells the API we want a SOAP 1.2 response, which is in XML format. If you remove the parameter, then you will receive an HTML response.

package Tests;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class Blog
{
	private static String url_SiteToTest = "http://www.example.com";

	public static void main(String[] args)
	{
		// Build URL for W3C HTML Markup Validator API
		String siteToTest = "http://validator.w3.org/check?output=soap12&uri=" + url_SiteToTest;

		// Get the response from W3C
		Document doc = GetValidationResultXML(siteToTest);

		if (doc != null)
		{
			// Parse the XML and write the results to the log
			ParseAndLog(doc, "Check HTML Markup");
		}
	}

	private static Document GetValidationResultXML(String siteToTest)
	{
		// Create a Document to hold the result
		Document doc = null;

		try
		{
			// Send request and save the response
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        doc = db.parse(new URL(siteToTest).openStream());
	        doc.normalize();
		}
		catch (Exception ex)
		{
			System.out.println(ex);
		}

		return doc;
	}

	private static void ParseAndLog(Document doc, String testName)
	{
		// In the interest of brevity I have omitted this code.
	}
}

You’ll notice the code (above) does not include ParseAndLog(). You can parse the XML using org.w3c.dom.

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