NamespaceAwareXmlDocumentBuilder implements XmlDocumentBuilder { @Override public Document buildDocument(final InputStream inputStream, final Schema schema) throws DocumentBuilderException { try { DocumentBuilderFactory dbFactory = documentBuilderFactoryBuilder.buildDocumentBuilderFactory(); dbFactory.setNamespaceAware(true); dbFactory.setSchema(schema); DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); document.getDocumentElement().normalize(); return document; } catch (Exception e) { throw new DocumentBuilderException("Exception while trying to parse XML document", e); } }  @Override Document buildDocument(final InputStream inputStream, final Schema schema);  }
@Test public final void testBuildDocumentShouldParseInputStreamToDocument() throws Exception { given(documentBuilderFactoryBuilder.buildDocumentBuilderFactory()).willReturn(documentBuilderFactory); given(documentBuilderFactory.newDocumentBuilder()).willReturn(documentBuilder); given(documentBuilder.parse(inputStream)).willReturn(document); Document actual = underTest.buildDocument(inputStream, null); verify(documentBuilderFactory).setNamespaceAware(true); verify(documentBuilder).parse(inputStream); assertEquals(actual, document); }
@Test(expectedExceptions = DocumentBuilderException.class) public final void testBuildDocumentShouldThrowExceptionWhenDocumentBuilderCannotBeCreated() throws Exception { given(documentBuilderFactoryBuilder.buildDocumentBuilderFactory()).willReturn(documentBuilderFactory); given(documentBuilderFactory.newDocumentBuilder()).willThrow(new ParserConfigurationException()); underTest.buildDocument(inputStream, null); }
@Test(expectedExceptions = DocumentBuilderException.class) public final void testBuildDocumentShouldThrowExceptionWhenParsingFails() throws Exception { given(documentBuilderFactoryBuilder.buildDocumentBuilderFactory()).willReturn(documentBuilderFactory); given(documentBuilderFactory.newDocumentBuilder()).willReturn(documentBuilder); given(documentBuilder.parse(inputStream)).willThrow(new SAXException()); underTest.buildDocument(inputStream, null); }