开发者

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 represent开发者_C百科ation in memory. But a StAX parser only takes FileReader( or I can play with the File Object)


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!)


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/


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);
>}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜