Saturday, December 7, 2013

compare formatted XML with unformated XML in unit test cases


How do we compare the XML in our unit test cases... 

For an instance, say

expected = "<com.mysamples.thoughtworks.xstream.SampleObject><name>Test</name><testInt>9</testInt></com.mysamples.thoughtworks.xstream.SampleObject>"

actual = "<com.mysamples.thoughtworks.xstream.SampleObject>
  <name>Test</name>
  <testInt>9</testInt>
</com.mysamples.thoughtworks.xstream.SampleObject>"

(the above actual is formatted xml)

then -> assertEqual (expected,actual) will result in FAILED test case,,

how do we correct this..
with simple regex make our unit testcases compare and pass

xml.replaceAll("[\\n\\s\\t]+", "")

//sample Snippet
@Test
public void simpleObjectToXMLStringVerifyTest() {
ObjectToXML obj = new ObjectToXML();
String xml = obj.toXMLString(sampleObj);
String expected = getExpectedStringOutOfSampleObject();
assertEquals(expected, xml.replaceAll("[\\n\\s\\t]+", ""));
}

No comments:

Post a Comment