The HTMLUnit Java framework helps developers to test implemented customer requirements. It allows developers to check the existence of HTML tags, submit or fill forms, click links and enables to test linked Java scripts of a web page. It represents a GUI-less browser. Furthermore you can emulate different browser how Firefox or Internet Explorer.
The example below checks two demands:
- First: Check existence of the banner image tag on the sobek agency page.
- Second: Force a form submit of the seo tool, which checks search engine compatibility of webpages.
The comments describes the usage of HTMLUnit in detail.
First test - Requested Page: http://sobek-agency.de:
package com.sobek.agency.htmlunit.example;
//imports
public class HtmlUnitTest {
@Test
public void testHeaderImageExists() throws Exception {
WebClient client = new WebClient();
HtmlPage mainPage = client.getPage("http://sobek-agency.de");
// test if banner div element exists and
// img banner image tag
try {
// check exist img banner div tag
HtmlDivision divTag =
mainPage.getBody().getElementById("banner");
// check exist img banner img tag
// iterate contained html tags
boolean bannerImgElementExists = false;
for (DomNode node:divTag.getChildren()) {
//is this node an image tag
if (node instanceof HtmlImage) {
HtmlImage bannerImageTag =
(HtmlImage)node;
//do i have the right src attribute value
if (bannerImageTag.getSrcAttribute()
.equals(
"/meshcms/themes/images/logo-full-header.jpg"
)) {
bannerImgElementExists = true;
}
}
}
// if not existing, test throws an ElementNotFoundException
if (bannerImgElementExists == false)
throw new ElementNotFoundException("img", "", "");
} catch (ElementNotFoundException notFound) {
fail();
}
}
}
Second test - Requested Pages: http://sobek-agency.de/produkte/seotool/ and by submitting form http://sobek-agency.de/seotool/index.jsp:
@Test
public void testSEOToolFormSubmit() throws Exception {
// get the seotool page that contains the HTML formular
HtmlPage seoFormPage =
client.getPage("http://sobek-agency.de/produkte/seotool/");
// the second form tag is the seo tool form
HtmlForm form = seoFormPage.getForms().get(1);
HtmlTextInput urlInputField = form.getInputByName("url");
// set url in text field
urlInputField.setValueAttribute("http://sobek-agency.de");
// after that we get the submit button
HtmlSubmitInput button = form.getInputByValue("Ok");
// and we force a submit
// the click method returns the result page
HtmlPage seoToolResultPage = button.click();
// get div tag, that contains head analysis results
HtmlDivision headResultsDiv =
seoToolResultPage.getBody().getElementById("1");
// the title result should be ok
String titleValue = headResultsDiv
.getElementsByTagName("table").get(0)
.getElementsByTagName("tr").get(0)
.getElementsByTagName("td").get(2)
.getTextContent();
assertTrue(titleValue.indexOf("Ok") != -1);
}
Technorati Tags: htmlunit webpage requirements




