2011-10-07 14 views
18

Sto scrivendo alcuni test di unità che passano deliberatamente stringhe errate al parser XML DOM Java.Come evitare che gli errori di analisi XML vengano scritti su System.err (stderr)?

E.g.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 

String message_xml = ""; // Empty string, not valid XML!!! 
ByteArrayInputStream input = new ByteArrayInputStream(message_xml.getBytes()); 
Document doc = db.parse(input); 

questo è correttamente gettando un SAXParseException (che è quello che si aspetta il mio test di unità). Ma è anche la scrittura di un messaggio a System.err (stderr) nella console Java:

[Fatal Error] :1:1: Premature end of file. 

C'è un modo per configurare il parser XML di non scrivere su stderr?

Sto usando Java 1.6SE.

+0

provare a configurare logger del pacchetto? Ma perché è importante - sono test unitari. –

risposta

24

installare il proprio ErrorHandler:

db.setErrorHandler(new ErrorHandler() { 
    @Override 
    public void warning(SAXParseException e) throws SAXException { 
     ; 
    } 

    @Override 
    public void fatalError(SAXParseException e) throws SAXException { 
     throw e; 
    } 

    @Override 
    public void error(SAXParseException e) throws SAXException { 
     throw e; 
    } 
}); 
Problemi correlati