### Question:
Jaxb2Printer extends Printer { @Override protected String serialize(Object input) throws XmlMappingException { StringWriter writer = new StringWriter(); jaxb2Marshaller.marshal(input, new StreamResult(writer)); return writer.toString(); } Jaxb2Printer(Jaxb2Marshaller jaxb2Marshaller);   }### Answer:
@Test public void serializeRoot() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setClassesToBeBound(Root.class); Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller); Root root = new Root(); root.setValue("value"); String xml = jaxb2Printer.serialize(root); assertThat(xml, is("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><someName><value>value</value></someName>")); }
@Test(expected = XmlMappingException.class) public void serializeXmlNotRoot() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setClassesToBeBound(Root.class); Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller); NotRoot notRoot = new NotRoot(); notRoot.setValue("value"); jaxb2Printer.serialize(notRoot); }
@Test(expected = MarshallingFailureException.class) public void serializeException() { Jaxb2Marshaller jaxb2Marshaller = mock(Jaxb2Marshaller.class); doThrow(new MarshallingFailureException("")).when(jaxb2Marshaller).marshal(any(), any()); Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller); Root root = new Root(); root.setValue("value"); jaxb2Printer.serialize(root); }
@Test(expected = MarshallingFailureException.class) public void serializeXmlEmpty() { Jaxb2Marshaller jaxb2Marshaller = mock(Jaxb2Marshaller.class); doThrow(new MarshallingFailureException("")).when(jaxb2Marshaller).marshal(any(), any()); Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller); Empty empty = new Empty(); empty.setValue("value"); jaxb2Printer.serialize(empty); }
@Test public void serializeJaxbElement() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setClassesToBeBound(Empty.class); Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller); Empty empty = new Empty(); empty.setValue("value"); JAXBElement<Empty> jaxbElement = new JAXBElement<>(new QName("localPart"), Empty.class, empty); String xml = jaxb2Printer.serialize(jaxbElement); assertThat(xml, is("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><localPart><value>value</value></localPart>")); }