Monday 1 August 2011

HtmlUnit



HtmlUnit provides an API to invoke web pages,fill the input fields,submit the forms.It is used to simulate the browser actions and is intended to use along with junit or testng .Apart,from testing HtmlUnit can also be used to grep the data from the browser and it supports many calls like getElementsByTagName("****"),getElementById("***"),getInputByName("****") etc.


The following sample code illustrates the use of HtmlUnit to input the fields and submit click action.This sounds similar to selenium,but here there is no browser invocation stuffs, it is  "GUI-Less browser for Java programs" and can capture the content of the browser,can be the data from tables,fields,container divs (similar to js functions nodes,cells,siblings etc).it also provides good support to js and ajax calls.






























The following case uses HtmlUnit along with Junit to test the web browser 





@Test
public void homePage_Firefox() throws Exception {
    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_2);
    final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
    assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());

    webClient.closeAllWindows();
}


More examples can be found here




cheers... happy coding !! :-)


No comments:

Post a Comment