1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.kim.api.test;
17
18 import javax.xml.bind.JAXBContext;
19 import javax.xml.bind.Marshaller;
20 import javax.xml.bind.Unmarshaller;
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.StringReader;
26 import java.io.StringWriter;
27
28 import static org.junit.Assert.assertEquals;
29
30
31
32
33
34
35
36
37 public final class JAXBAssert {
38
39 private JAXBAssert() {}
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 public static void assertEqualXmlMarshalUnmarshal(Object objectToMarshal, String expectedXml, Class<?> ... classesToBeBound) {
58 String marshaledXml = null;
59 try {
60 JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound);
61 Marshaller marshaller = jaxbContext.createMarshaller();
62
63 StringWriter stringWriter = new StringWriter();
64
65 marshaller.marshal(objectToMarshal, stringWriter);
66
67 marshaledXml = stringWriter.toString();
68
69 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
70
71 Object actual = unmarshaller.unmarshal(new StringReader(stringWriter.toString()));
72 assertEquals("Unmarshalled object should be equal to original objectToMarshall.", objectToMarshal, actual);
73
74 Object expected = unmarshaller.unmarshal(new StringReader(expectedXml.trim()));
75 assertEquals("Unmarshalled objects should be equal.", expected, actual);
76 } catch (Throwable e) {
77 System.err.println("Outputting marshaled XML from failed assertion:\n" + marshaledXml);
78 if (e instanceof RuntimeException) {
79 throw (RuntimeException)e;
80 } else if (e instanceof Error) {
81 throw (Error)e;
82 }
83 throw new RuntimeException("Failed to marshall/unmarshall with JAXB. See the nested exception for details.", e);
84 }
85 }
86
87 public static void assertEqualXmlMarshalUnmarshalWithResource(Object objectToMarshal, InputStream expectedXml, Class<?> ... classesToBeBound) throws IOException {
88 BufferedReader reader = new BufferedReader(new InputStreamReader(expectedXml));
89 StringWriter writer = new StringWriter();
90 int data = -1;
91 while ((data = reader.read()) != -1) {
92 writer.write(data);
93 }
94 assertEqualXmlMarshalUnmarshal(objectToMarshal, writer.toString(), classesToBeBound);
95 }
96
97
98 }