tags:

views:

34

answers:

3

Hi,

My question is:

In JUnit, How do I setup xml data for my System Under Test(SUT) without making the SUT read from an XML file physically stored on the file system

Background:

I am given a XML file which contains rules for creation of an invoice. My job is to convert these rules from XMl to Java Objects e.g. If there is a tag as below in my XML file which indicates that after a period of 30 days, the transaction cannot be invoiced

<ExpirationDay>30</ExpirationDay> 

this converts to a Java class , say ExpirationDateInvoicingRule

I have a class InvoiceConfiguration which should take the XML file and create the *InvoicingRule objects. I am thinking of using StAX to parse the XML document within InvoiceConfiguration

Problem:

I want to unit test InvoiceConfiguration. But I dont want InvoiceConfiguration to read from an xml file physically on the file system . I want my unit test to be independent of any physical stored xml file. I want to create a xml representation in memory. But a StAX parser only takes FileReader( or I can play with the File Object)

A: 

Refactor your code to take a Reader instead of opening a File. The File opening can be done separately (and is largely untestable if you want to stick to the rule of not accessing files in unit tests - but that's OK, because it's just one line and you can't really get it wrong!)

dty
A: 

Here is an example of quite a few tests that use both XMLUnit and a custom framework for processing XML. The framework uses StAX to map XML to Java POJOs.

https://simple.svn.sourceforge.net/svnroot/simple/trunk/download/stream/src/test/java/org/simpleframework/xml/core/

There are no external dependencies, and test coverage is approx 90%

http://simple.sourceforge.net/download/stream/report/cobertura/

ng
A: 

Thanks guys for your help. Another good source is this link: http://marc.info/?l=xerces-j-dev&amp;m=86952145010437&amp;w=2

This is the answer from Baq Haidri

-----Original Message----- From: Baq Haidri [mailto:bhaidri@....]

I found this in a book called 'Professional XML' by Wrox publishing:

>
>public void parseString(String s) throws SAXException, IOException
>{
>         StringReader reader = new SringReader(s);
>         InputSource source = new InputSource(reader);
>         parser.parse(source);
>}

RAbraham