Xml string representation of expected result for Junit test
I'm writing a Junit test in which the expected result is a XML string. What's the best way represent the expected string? Right now I have it as a stringBuilder and I do the following. I want to assert that the actual and expected are same. What would be the most efficient way to represent this expected string? Also I don't want anyone to alter the expected string so it should be final too.
@Before
public void setUp() {
expected.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
expected.append("<n-relationship guid=\"IEEBFAD40BC5711DFAE41F5F92790F896\" control=\"add\">");
expected.append("<n-relbase>ID17A8B10BC5711DFAE41F5F92790F896</n-relbase><n-reltype>IPLS</n-reltype>");
expected.append("<ip.content><pub.no>1234567</pub.开发者_JAVA百科no>");
expected.append("<event.date>2010-09-10</event.date><event.code>02394802323</event.code>");
expected.append("<event.treatment>+</event.treatment><event.description>OPPOSITION DISMISSED</event.description>");
expected.append("</ip.content></n-relpayload></n-relationship");
}
a) XML does not belong inside java code. Put it in the same package (preferably in the src/main/resources folder if you use maven) and load it as a resource.
b) Don't do a string comparison with XML: do an XML structure comparison. The canonicalizer is a great idea.
This is harder than it looks - string comparisons will certainly fail. This is because at least
- different representations for same entity (& apos;, etc.)
- different order of attributes
- different quotes
- whitespace
The simplest way is to canonicalise the XML in both the expected and test and compare those. All good XML tools should have a canonicalizer.
I have had to write a lot of XML machinery to support my Unit tests - admittedly they contain floating point numbers and I have to allow for rounding errors.
But comparing strings will certainly fail.
Comparing 2 XML using their String representation is dangerous. Indeed, do you consider the following XML :
<foo>
<bar>xxx</bar>
<baz>yyy</baz>
</foo>
equals to:
<foo>
<baz>yyy</baz>
<bar>xxx</bar>
</foo>
?
If yes, then I suggest that you use XMLUnit to test your current XML with the expected one.
Regarding the expected XML, the best way is to store them as external files, and load them during your test (in a @BeforeClass
snippet for example).
I think you are on the correct track -- define a string constant "EXPECTED_XML" and just assert off that.
精彩评论