Thursday, March 22nd, 2007

Automatic testing of Ajax from Java

Category: Java, Testing

Ed Burns (of Sun and the JSF expert group) has created an automated testing framework for Ajax in Java called MCP.

This framework stems from an old, old Mozilla project called the Mozilla Web Client started in 1999 as a part of the Sun/AOL/Netscape alliance. The ambitious misson statement of the project is:

The webclient project aims to provide the premier browser-neutral Java API that enables generic web browsing capability. This capability includes, but is not limited to: web content rendering, navigation, a history mechanism, and progress notification. The actual capabilities implemented depend on the underlying browser implementation.

You can tie unit tests into browser ajax events by using an AjaxListener and getting access to items such as the responseText/responseXML/HTTP headers, and more.

  1. AjaxListener listener = new AjaxListener() {
  2. public void endAjax(Map eventMap) {
  3.           bitSet.flip(TestFeature.RECEIVED_END_AJAX_EVENT.ordinal());
  4.           if (null != eventMap) {
  5.               bitSet.flip(TestFeature.HAS_MAP.ordinal());
  6.           }
  7.           // Make some assertions about the response text
  8.           String responseText = (String) eventMap.get("responseText");
  9.           if (null != responseText) {
  10.               if (-1 != responseText.indexOf("<partial -response>") &&
  11.                   -1 != responseText.indexOf("</partial>")) {
  12.                 bitSet.flip(TestFeature.HAS_VALID_RESPONSE_TEXT.ordinal());
  13.               }
  14.           }
  15.           Document responseXML = (Document)
  16.               eventMap.get("responseXML");
  17.           Element rootElement = null, element = null;
  18.           Node node = null;
  19.           String tagName = null;
  20.           try {
  21.               rootElement = responseXML.getDocumentElement();
  22.               tagName = rootElement.getTagName();
  23.               if (tagName.equals("partial-response")) {
  24.                   element = (Element) rootElement.getFirstChild();
  25.                   tagName = element.getTagName();
  26. ...

Check out the two part screencast of this in action:

Part One, Part Two.

Posted by Dion Almaer at 2:39 pm
3 Comments

+++--
3.6 rating from 27 votes

3 Comments »

Comments feed TrackBack URI

Would this be similiar to HTMLUnit? Would there be advantages to this over HTMLUnit?

Comment by Kris Zyp — March 23, 2007

It fills this requirement which htmlunit currently does not:

Allows writing tests that make assertions about the response to Ajax requests.

Comment by Ed Burns — March 23, 2007

Ed,
How does this relate to JRex?

Comment by Patrick Lightbody — March 23, 2007

Leave a comment

You must be logged in to post a comment.