2012-11-14 12 views
6

JUnitテストのマーシャリング時にJAXBExceptionを強制する方法を見つけることができませんでした。誰にもアイデアはありますか?ここで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; 
    } 

答えて

3

marshal動作中​​を作成するためのさまざまな方法があります。

1 - 無効なオブジェクトをマーシャリング

は、あなたが生成することができますをマーシャリングする際に、JAXBContextが認識していないクラスのインスタンスをマーシャリングすることによって(つまり、あなたのexamplをとるeを使用して、Fooのインスタンスをマーシャリングするために使用します)。これにより、次の例外が発生します。

FileOutputStream closedStream = new FileOutputStream("src/foo.xml"); 
    closedStream.close(); 
    jaxbMarshaller.marshal(this, closedStream); 

次にあなたがMarshalExceptionを取得します: -

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) 

2は元帥あなたは、このような閉じられたOutputStream無効として出力にマーシャリングしようとした場合

無効な出力へ​​のサブクラスです。

Exception in thread "main" javax.xml.bind.MarshalException 
- with linked exception: 
[java.io.IOException: Stream Closed] 
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:320) 
    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) 
Caused by: java.io.IOException: Stream Closed 
    at java.io.FileOutputStream.writeBytes(Native Method) 
    at java.io.FileOutputStream.write(FileOutputStream.java:318) 
    at com.sun.xml.bind.v2.runtime.output.UTF8XmlOutput.flushBuffer(UTF8XmlOutput.java:413) 
    at com.sun.xml.bind.v2.runtime.output.UTF8XmlOutput.endDocument(UTF8XmlOutput.java:137) 
    at com.sun.xml.bind.v2.runtime.output.IndentingUTF8XmlOutput.endDocument(IndentingUTF8XmlOutput.java:165) 
    at com.sun.xml.bind.v2.runtime.XMLSerializer.endDocument(XMLSerializer.java:852) 
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.postwrite(MarshallerImpl.java:369) 
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:316) 
    ... 3 more 
関連する問題