How to create a ParserConfigurationException when creating a new XML file through DocumentBuidlerFactory

I am going to create XML from a string. He looks like

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; public Document createCompleteExportXml(String xmlFilename, String content) { try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); //create the XML file here } catch (ParserConfigurationException pce) { LOGGER.trace("parsing error ", pce); } } 

Now I have to check if the exception can get into the Junit test.

 @Test(expected=ParserConfigurationException.class) public void createCompleteExportXmlWithParseConfigurationException() { String xmlFilename = "junitExportTestWithParseConfigurationException.xml"; String content = "any content"; XmlFileWriter writer = new XmlFileWriter(); Document doc = writer.createCompleteExportXml(xmlFilename, content); } 

How can I make this test throw a ParserConfigurationException ?

I am making my question more specific: how can I make documentFactory.newDocumentBuilder () not work because "DocumentBuilder cannot be created that satisfies the requested configuration"? Where is the configuration? How can I change it intentionally wrong?

+5
source share
3 answers

Your test fails because you definitely catch a ParserConfigurationException in your method, so you never threw it. To pass the test:

1) change the signature of your method (throw exception)

 public String createCompleteExportXml(String xmlFilename, String content) throws ParserConfigurationException { 

2) Throw a ParserConfigurationException . To do this, you can remove the catch block or throw an exception after LOGGER.trace . An example for the second option:

  try { //... } catch (ParserConfigurationException pce) { LOGGER.trace("parsing error ", pce); throw pce; } 

Hope this helps you

[UPDATE]

If you want to simulate a ParserConfigurationException , you can use a framework like Mockito / PowerMock for the mock DocumentBuilderFactory and mimic that the ParserConfigurationException is ParserConfigurationException when the newDocumentBuilder() method is newDocumentBuilder() .

Example:

 @RunWith(PowerMockRunner.class) @PrepareForTest(DocumentBuilderFactory.class) public class XmlFileWriterTest { @Test(expected = ParserConfigurationException.class) public void createCompleteExportXmlWithParseConfigurationException() throws Exception { String xmlFilename = "junitExportTestWithParseConfigurationException.xml"; String content = "any content"; XmlFileWriter writer = new XmlFileWriter(); // Mock DocumentBuilderFactory: When method newDocumentBuilder() is called, throws a simulated ParserConfigurationException DocumentBuilderFactory mockDocumentBuilderFactory = PowerMockito.mock(DocumentBuilderFactory.class); PowerMockito.when(mockDocumentBuilderFactory.newDocumentBuilder()).thenThrow(new ParserConfigurationException("Simulated ex")); // Mock DocumentBuilderFactory.newInstance(), when is called, returns your mock instance mockDocumentBuilderFactory PowerMockito.mockStatic(DocumentBuilderFactory.class); PowerMockito.when(DocumentBuilderFactory.newInstance()).thenReturn(mockDocumentBuilderFactory); writer.createCompleteExportXml(xmlFilename, content); } 

This test pass (with previous code suggestions).

Maven dependencies for powerMock:

 <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.5.4</version> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.5.4</version> </dependency> 

Hope this will be what you are looking for.

You can find additional documentation for Mockito and PowerMock.

+2
source

As you can see in the source code :

  public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { // Check that if a Schema has been specified that neither of the schema properties have been set. if (grammar != null && attributes != null) { if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) { throw new ParserConfigurationException( SAXMessageFormatter.formatMessage(null, "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE})); } else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) { throw new ParserConfigurationException( SAXMessageFormatter.formatMessage(null, "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE})); } } try { return new DocumentBuilderImpl(this, attributes, features, fSecureProcess); } catch (SAXException se) { // Handles both SAXNotSupportedException, SAXNotRecognizedException throw new ParserConfigurationException(se.getMessage()); } } 

if the schema is defined twice, a ParserConfigurationException is raised, for example,

+3
source

I do not think that any of the existing answers really answered the question, so here I take it upon myself.

Approach one using com.sun's internal components. *:

(helper class)

 import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.validation.Schema; import javax.xml.validation.Validator; import javax.xml.validation.ValidatorHandler; public class MisconfiguredDocumentBuilderFactory extends DocumentBuilderFactoryImpl { @Override public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { super.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); super.setSchema(new Schema() { @Override public Validator newValidator() { return null; } @Override public ValidatorHandler newValidatorHandler() { return null; } }); return super.newDocumentBuilder(); } } 

(Actual test class)

 public class OPClassTest { private final static String DOC_BUILDER_PROPERTY_NAME = "javax.xml.parsers.DocumentBuilderFactory"; @Test public void testParserConfigurationProblem() { System.setProperty(DOC_BUILDER_PROPERTY_NAME, MisconfiguredDocumentBuilderFactory.class.getCanonicalName()); targetClass.createCompleteExportXml("somefilename", "somecontent"); } @After public void tearDown() { System.clearProperty(DOC_BUILDER_PROPERTY_NAME); } } 

Approach 2 without using com.sun. * namespaces

(helper class)

 import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; public class MisconfiguredDocumentBuilderFactory2 extends DocumentBuilderFactory { @Override public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { throw new ParserConfigurationException( "this factory is not configured properly"); } @Override public void setAttribute(String name, Object value) throws IllegalArgumentException { // no-op } @Override public Object getAttribute(String name) throws IllegalArgumentException { return null; } @Override public void setFeature(String name, boolean value) throws ParserConfigurationException { // no-op } @Override public boolean getFeature(String name) throws ParserConfigurationException { return false; } } 

(Actual test class)

 public class OPClassTest { private final static String DOC_BUILDER_PROPERTY_NAME = "javax.xml.parsers.DocumentBuilderFactory"; @Test public void testParserConfigurationProblem() { System.setProperty(DOC_BUILDER_PROPERTY_NAME, MisconfiguredDocumentBuilderFactory2.class.getCanonicalName()); targetClass.createCompleteExportXml("somefilename", "somecontent"); } @After public void tearDown() { System.clearProperty(DOC_BUILDER_PROPERTY_NAME); } } 
+1
source

Source: https://habr.com/ru/post/1201733/


All Articles