Search code examples
xmljunitstax

Unit Testing XML independent of physical XML file


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 don't 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)


Solution

  • Thanks guys for your help. Another good source is this link: http://marc.info/?l=xerces-j-dev&m=86952145010437&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);
    >}