- HtmlUnit is an open source java library for creating HTTP calls which imitate the browser functionality.
- HtmlUnit is mostly used for integration testing upon Unit test frameworks such as JUnit or TestNG. This is done by requesting web pages and asserting the results.
Simple Example
@Test
public void testGoogle(){
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals("Google", currentPage.getTitleText());
}
WebClient
- As you can see in the example, the WebClient is the starting point. It is the browser simulator.
- WebClient.getPage() is just like typing an address in the browser. It returns an HtmlPage object.
HtmlPage
- HtmlPage represents a single web page along with all of it’s client’s data (HTML, JavaScript, CSS …).
- The HtmlPage lets you access to many of a web page content:
Page source
- You can receive the page source as text or as XML.
HtmlPage currentPage =
webClient.getPage("http://www.google.com/");
String textSource = currentPage.asText();
String xmlSource = currentPage.asXml();
HTML Elements
- HtmlPage lets you ability to access any of the page HTML elements and all of their attributes and sub elements. This includes tables, images, input fields, divs or any other Html element you may imagine.
- Use the function getHtmlElementById() to get any of the page elements.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlImage imgElement = (HtmlImage)currentPage.getHtmlElementById("logo");
System.out.println(imgElement.getAttribute("src"));
Anchors
- Anchor is the representation of the Html tag <a href=”…” >link</a>.
- Use the functions getAnchorByName(), getAnchorByHref() and getAnchorByText() to easily access any of the anchors in the page.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlAnchor advancedSearchAn =
currentPage.getAnchorByText("Advanced Search");
currentPage = advancedSearchAn.click();
assertEquals("Google Advanced Search",currentPage.getTitleText());
Dom elements by XPath
- You can access any of the page elements by using XPath.
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=avi");
//Using XPath to get the first result in Google query
HtmlElement element = (HtmlElement)currentPage.getByXPath("//h3").get(0);
DomNode result = element.getChildNodes().get(0);
Form control
- A large part of controlling your HTML page is to control the form elements:
- HtmlForm
- HtmlTextInput
- HtmlSubmitInput
- HtmlCheckBoxInput
- HtmlHiddenInput
- HtmlPasswordInput
- HtmlRadioButtonInput
- HtmlFileInput
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
//Get the query input text
HtmlInput queryInput = currentPage.getElementByName("q");
queryInput.setValueAttribute("aviyehuda");
//Submit the form by pressing the submit button
HtmlSubmitInput submitBtn = currentPage.getElementByName("btnG");
currentPage = submitBtn.click();
Tables
currentPage = webClient.getPage("http://www.google.com/search?q=htmlunit");
final HtmlTable table = currentPage.getHtmlElementById("nav");
for (final HtmlTableRow row : table.getRows()) {
System.out.println("Found row");
for (final HtmlTableCell cell : row.getCells()) {
System.out.println(" Found cell: " + cell.asText());
}
}
JavaScript support
- HtmlUnit uses the Mozilla Rhino JavaScript engine.
- This lets you the ability to run pages with JavaScript or even run JavaScript code by command.
ScriptResult result = currentPage.executeJavaScript(JavaScriptCode);
- By default JavaScript exceptions will crash your tests. If you wish to ignore JavaScript exceptions use this:
webClient().setThrowExceptionOnScriptError(false);
- If you would like to turn off the JavaScript all together, use this:
currentPage.getWebClient().setJavaScriptEnabled(false);
HTTP elements
URL
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.co.uk/search?q=htmlunit");
URL url = currentPage.getWebResponse().getRequestSettings().getUrl()
Response status
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());
Cookies
Set<Cookie> cookies = webClient.getCookieManager().getCookies();
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + " = " + cookie.getValue());
}
Response headers
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=htmlunit");
List<NameValuePair> headers =
currentPage.getWebResponse().getResponseHeaders();
for (NameValuePair header : headers) {
System.out.println(header.getName() + " = " + header.getValue());
}
Request parameters
List<NameValuePair> parameters =
currentPage.getWebResponse().getRequestSettings().getRequestParameters();
for (NameValuePair parameter : parameters) {
System.out.println(parameter.getName() + " = " + parameter.getValue());
}
Making assertions
- HtmlUnit comes with a set of assetions:
assertTitleEquals(HtmlPage, String) assertTitleContains(HtmlPage, String) assertTitleMatches(HtmlPage, String) assertElementPresent(HtmlPage, String) assertElementPresentByXPath(HtmlPage, String) assertElementNotPresent(HtmlPage, String) assertElementNotPresentByXPath(HtmlPage, String) assertTextPresent(HtmlPage, String) assertTextPresentInElement(HtmlPage, String, String) assertTextNotPresent(HtmlPage, String) assertTextNotPresentInElement(HtmlPage, String, String) assertLinkPresent(HtmlPage, String) assertLinkNotPresent(HtmlPage, String) assertLinkPresentWithText(HtmlPage, String) assertLinkNotPresentWithText(HtmlPage, String) assertFormPresent(HtmlPage, String) assertFormNotPresent(HtmlPage, String) assertInputPresent(HtmlPage, String) assertInputNotPresent(HtmlPage, String) assertInputContainsValue(HtmlPage, String, String) assertInputDoesNotContainValue(HtmlPage, String, String)
- You can still of course use the framework’s assertions. For example, if you are using JUnit, you can still use assertTrue() and so on.
- Here are a few examples:
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=htmlunit");
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());
WebAssert.assertTextPresent(currentPage, "htmlunit");
WebAssert.assertTitleContains(currentPage, "htmlunit");
WebAssert.assertLinkPresentWithText(currentPage, "Advanced search");
assertTrue(currentPage.getByXPath("//h3").size()>0); //result number
assertNotNull(webClient.getCookieManager().getCookie("NID"));
See also
| Opening a new screen is fairly easy in android. This post will show you almost all you need to know about switching back and forth between screens in your Android application. |
Add all activities to manifest
- Each screen is usually an Activity.
- Each activity should be mentioned in the manifest file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.aviyehuda.puzzle" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="MyActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MyActivity2" > </activity> </application> <uses-sdk android:minSdkVersion="6" /> </manifest>
The simple use
Intent in = new Intent(MyActivity.this, MyActivity2.class); startActivity(in);
- Bear in mind that every time you will call the function startActivity(intent) a new instance of MyActivity2 will be created.
Passing a parameter
- In most times you need to pass a parameter to the new screen. You do that by using the function putExtra().
- This function
Intent in = new Intent(myactivity.this, MyActivity2.class);
in.putExtra("myKey", "new1");
startActivity(in);
Receiving a parameter
- And of course you will need to receive that parameter on the other side.
String s= getIntent().getExtras().get("myKey").toString()
Going back
- If you need to go back to the previous screen and terminate the current screen, than all you have to do is to use the function finish() from anywhere in the new Activity.
finish();
Open for result
- When you need to open a new screen and get result back from it, than use the function startActivityForResult() instead of startActivity()
Intent in = new Intent(myactivity.this, MyActivity2.class); startActivityForResult(in, 0);
Returning a result
Intent in = getIntent();
in.putExtra("result", "some parameter");
setResult(RESULT_OK,in);
finish();
Getting the result from the new activity
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Result",""+data.getExtras().get("result"));
}
I first got into the magical world of the internet in the happy 90′s. Back then you could find 3 basic types of network application clients: Internet lightweight web sites (HTML, JS), installed applications with network connection like ICQ or Applets.
The years went by, the internet connection got faster and richer applications came out of the desktop and into the browser. The web applications clients became fatter. Even if the desktop applications still exist, they have clearly become a lot less common. That was about the time I started developing in java.
The obvious solution for many of these fat clients were the java web frameworks like Struts, JSF and all the others. But as the years went by a new approach became more and more popular – the Ajax web applications, with GMail in the lead.
Fat clients never looked better and the usability was excellent. It is almost as if we are using desktop applications (!?!). JavaScript was never so cool. Libraries like JQuery are born every day as well as some new solutions like GWT to make our life with JavaScript easier.
But the story doesn’t end here. With the birth of the smart cellphones an old player came back to life – that’s right, the installed application. The small screen and slow connection makes the rich client web sites a bit hard to handle. IPhone followed by Android and Blackberry clearly encourage this approach with their application markets, so obviously installed applications are dominators in the mobile network applications arena.
But what’s next? Will the mobile installed applications suffer the same fate as the desktop applications? Clearly the arrival of HTML5 won’t make their life easier. Or maybe the installed applications will survive with the help of technologies such as JavaFX. Maybe both will manage to have a share.
What do you think?

Recent Comments
dante on Weekend project: Bluetooth multisender
how i send image to the devices from java using bluecove?????, this is part of may final proyect please give...Karol on Android – Multithreading in a UI environment
Hi All the examples I see so far implement the Runnable object as inner class of the main...faisal on Memory Game – Android Application
Hi, You have done excellent job. Very nice. Though I tried to build it but it did not build. Could you please...Avi on How to use fiddler+firefox to download files from streaming sites.
Try searching "Mpeg layer-3" instead.ashi on How to use fiddler+firefox to download files from streaming sites.
hi, i tried above i downloaded fiddler2 and also the script editor... also pasted the code but but i have problem in step...Rui Pedrosa on Android – Multithreading in a UI environment
A simple but very useful explanation! thanks!Hui Sunray on Using Hibernate Validator to cover your validation needs
I like your examplesSridhar on Weekend project: Bluetooth multisender
Excellent work and it is sending to many bluetooth devicesjetti on Android Development – Preferences
Hi, How can I add Icon/Image to each item in ListPreference? Is it possible to add our own icons...Eric on Android – Multithreading in a UI environment
Thx, helped alot :)