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