如何在编组JUnit测试时强制执行JAXBException

时间:2012-11-14 23:37:04

标签: jaxb

在编组JUnit测试时,我无法找到强制JAXBException的方法。有没有人有任何想法?

这是我的编组代码:

   public String toXml() {
          log.debug("Entered toXml method");
    String result = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter writer = new StringWriter();
        jaxbMarshaller.marshal(this, writer);
        result = writer.toString();
    } catch (JAXBException e) {
          log.error(e);
    }
          log.debug("Exiting toXml method");
    return result;
   }

1 个答案:

答案 0 :(得分:3)

JAXBException操作期间,有多种方法可以创建marshal

1 - Marshal a Invalid Object

您可以在编组操作期间通过编组JAXBException不知道的类的实例来生成JAXBContext(例如,使用它来编组{{1}的实例1}})。这将产生以下异常。

Foo

2 - Marshal到无效输出

如果您尝试编组一个无效的输出,例如已关闭的Exception in thread "main" javax.xml.bind.JAXBException: class forum13389277.Foo nor any of its super class is known to this context. at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:594) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:482) at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:315) at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:244) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:95) at forum13272288.Demo.main(Demo.java:27)

OutputStream

然后你会得到一个 FileOutputStream closedStream = new FileOutputStream("src/foo.xml"); closedStream.close(); jaxbMarshaller.marshal(this, closedStream); ,它是MarshalException的子类。

JAXBException