Home > database >  How to mock original XML output to use in test class in Java?
How to mock original XML output to use in test class in Java?

Time:03-17

I am writing Junit test cases for an Application and again and again I have to build dummy Document object and set root element and every other elements according to my original response so as to pass in my Mockito.when(m1()).thenReturn(respDoc). The code is something like this

Code Starts

Document respDoc = new Document();
Element elem = new Element("RootElement");
respDoc.setRootElement(elem);
Element node1 = new Element("Nodes").addContent("FirstNode");
elem.add(node1);
 **And So On...**

Code Ends

Sometimes the response xml is so big that it takes all of my time just to create this Document object. Is there any way where I can just pass this whole XML and it gives me the desired output.

Please let me know if theres any confusion. Thanks in advance!

CodePudding user response:

Assuming Document is from JDOM Library:

You need the following dependency:

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Then you parse it:

  import org.jdom2.Document;
  import org.jdom2.input.SAXBuilder;


  String FILENAME = "src/main/resources/staff.xml";

  SAXBuilder sax = new SAXBuilder();

  Document doc = sax.build(new File(FILENAME));

  Mockito.when(m1()).thenReturn(doc);

Reference: https://mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/


Well the documentation states you can use an InputStream:

http://www.jdom.org/docs/apidocs/org/jdom2/input/SAXBuilder.html Example:

String yourXmlString = "<xml>";

InputStream stringStream = new ByteArrayInputStream(yourXmlString .getBytes("UTF-8"));

SAXBuilder sax = new SAXBuilder();
 
Document doc = sax.build(stringStream );
  • Related