1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.test.util;
18
19 import java.io.StringReader;
20 import java.util.Map;
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.transform.Source;
24 import javax.xml.transform.dom.DOMSource;
25
26 import org.custommonkey.xmlunit.Diff;
27 import org.custommonkey.xmlunit.XMLUnit;
28 import org.hamcrest.Matcher;
29 import org.w3c.dom.Document;
30 import org.w3c.dom.Node;
31 import org.xml.sax.InputSource;
32
33 import static org.springframework.test.util.MatcherAssertionErrors.*;
34
35
36
37
38
39
40
41 public class XmlExpectationsHelper {
42
43
44
45
46 public void assertNode(String content, Matcher<? super Node> matcher) throws Exception {
47 Document document = parseXmlString(content);
48 assertThat("Body content", document, matcher);
49 }
50
51 private Document parseXmlString(String xml) throws Exception {
52 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
53 factory.setNamespaceAware(true);
54 DocumentBuilder documentBuilder = factory.newDocumentBuilder();
55 InputSource inputSource = new InputSource(new StringReader(xml));
56 return documentBuilder.parse(inputSource);
57 }
58
59
60
61
62
63 public void assertSource(String content, Matcher<? super Source> matcher) throws Exception {
64 Document document = parseXmlString(content);
65 assertThat("Body content", new DOMSource(document), matcher);
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79 public void assertXmlEqual(String expected, String actual) throws Exception {
80 XMLUnit.setIgnoreWhitespace(true);
81 XMLUnit.setIgnoreComments(true);
82 XMLUnit.setIgnoreAttributeOrder(true);
83
84 Document control = XMLUnit.buildControlDocument(expected);
85 Document test = XMLUnit.buildTestDocument(actual);
86 Diff diff = new Diff(control, test);
87 if (!diff.similar()) {
88 AssertionErrors.fail("Body content " + diff.toString());
89 }
90 }
91
92 }