Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test my HtmlUnit code with an xml file

Tags:

java

htmlunit

I am writing an application that uses HtmlUnit to screen scrape some data. The logic of which fields come from which parts of the page, and the XPath to retrieve them is getting a bit complicated, so before I refactor I want to write some simple unit tests. I have used the 'page.asXml()' method to get the page XML and save that as a file in my test resources folder, but how can I load it back in as an HtmlPage?

eg

    HtmlPage page = webClient.getPage(url);
    System.out.println(page.asXml());

Now in my unit test I want to do the equivalent of:

    HtmlPage page = new HtmlPage(myXmlTestFile);

But I can't seem to find anything that will do this. Any ideas?

like image 289
Matt Avatar asked Dec 09 '13 15:12

Matt


People also ask

What is XML in testing?

XML is an electronic communication message format that contains data and Database is a physical storage with tables/columns containing data. Most applications exchange data with each other. These communications may be in the form of XML messages that contain data.


1 Answers

My final solution (concatenated from a number of other SO posts):

    URL url = new URL("http://www.example.com");

    InputStream is = this.getClass().getClassLoader().getResourceAsStream("myPageXmlFile.xml");
    String xmlPageString = IOUtils.toString(is);

    StringWebResponse response = new StringWebResponse(xmlPageString, url);
    WebClient client = WebClientConnector.createWebClient(false); // helper method for creating a WebClient instance
    HtmlPage page = HTMLParser.parseXHtml(response, client.getCurrentWindow());
like image 195
Matt Avatar answered Oct 28 '22 12:10

Matt