This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,44 @@
package com.baeldung.sax;
import org.junit.Test;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.*;
public class SaxParserMainUnitTest {
@Test
public void givenAProperXMLFile_whenItIsParsed_ThenAnObjectContainsAllItsElements() throws IOException, SAXException, ParserConfigurationException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
SaxParserMain.BaeldungHandler baeldungHandler = new SaxParserMain.BaeldungHandler();
saxParser.parse("src/test/resources/sax/baeldung.xml", baeldungHandler);
SaxParserMain.Baeldung result = baeldungHandler.getWebsite();
assertNotNull(result);
List<SaxParserMain.BaeldungArticle> articles = result.getArticleList();
assertNotNull(articles);
assertEquals(3, articles.size());
SaxParserMain.BaeldungArticle articleOne = articles.get(0);
assertEquals("Parsing an XML File Using SAX Parser", articleOne.getTitle());
assertEquals("SAX Parser's Lorem ipsum...", articleOne.getContent());
SaxParserMain.BaeldungArticle articleTwo = articles.get(1);
assertEquals("Parsing an XML File Using DOM Parser", articleTwo.getTitle());
assertEquals("DOM Parser's Lorem ipsum...", articleTwo.getContent());
SaxParserMain.BaeldungArticle articleThree = articles.get(2);
assertEquals("Parsing an XML File Using StAX Parser", articleThree.getTitle());
assertEquals("StAX Parser's Lorem ipsum...", articleThree.getContent());
}
}
@@ -0,0 +1,82 @@
package com.baeldung.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DefaultParserUnitTest {
final String fileName = "src/test/resources/example_default_parser.xml";
final String fileNameSpace = "src/test/resources/example_default_parser_namespace.xml";
DefaultParser parser;
@Test
public void getFirstLevelNodeListTest() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getFirstLevelNodeList();
assertNotNull(list);
assertTrue(list.getLength() == 4);
}
@Test
public void getNodeListByTitleTest() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("XML");
for (int i = 0; null != list && i < list.getLength(); i++) {
Node nod = list.item(i);
assertEquals("java", nod.getAttributes().getNamedItem("type").getTextContent());
assertEquals("02", nod.getAttributes().getNamedItem("tutId").getTextContent());
assertEquals("XML", nod.getFirstChild().getTextContent());
assertEquals("title", nod.getFirstChild().getNodeName());
assertEquals("description", nod.getChildNodes().item(1).getNodeName());
assertEquals("Introduction to XPath", nod.getChildNodes().item(1).getTextContent());
assertEquals("author", nod.getLastChild().getNodeName());
assertEquals("XMLAuthor", nod.getLastChild().getTextContent());
}
}
@Test
public void getNodeByIdTest() {
parser = new DefaultParser(new File(fileName));
Node node = parser.getNodeById("03");
String type = node.getAttributes().getNamedItem("type").getNodeValue();
assertEquals("android", type);
}
@Test
public void getNodeListByDateTest() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("04022016");
for (int i = 0; null != list && i < list.getLength(); i++) {
Node nod = list.item(i);
assertEquals("java", nod.getAttributes().getNamedItem("type").getTextContent());
assertEquals("04", nod.getAttributes().getNamedItem("tutId").getTextContent());
assertEquals("Spring", nod.getFirstChild().getTextContent());
assertEquals("title", nod.getFirstChild().getNodeName());
assertEquals("description", nod.getChildNodes().item(1).getNodeName());
assertEquals("Introduction to Spring", nod.getChildNodes().item(1).getTextContent());
assertEquals("author", nod.getLastChild().getNodeName());
assertEquals("SpringAuthor", nod.getLastChild().getTextContent());
}
}
@Test
public void getNodeListWithNamespaceTest() {
parser = new DefaultParser(new File(fileNameSpace));
NodeList list = parser.getAllTutorials();
assertNotNull(list);
assertTrue(list.getLength() == 4);
}
}
@@ -0,0 +1,87 @@
package com.baeldung.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import org.dom4j.Element;
import org.dom4j.Node;
import org.junit.Test;
public class Dom4JParserUnitTest {
final String fileName = "src/test/resources/example_dom4j.xml";
Dom4JParser parser;
@Test
public void getRootElementTest() {
parser = new Dom4JParser(new File(fileName));
Element root = parser.getRootElement();
assertNotNull(root);
assertTrue(root.elements().size() == 4);
}
@Test
public void getFirstElementListTest() {
parser = new Dom4JParser(new File(fileName));
List<Element> firstList = parser.getFirstElementList();
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).attributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new Dom4JParser(new File(fileName));
Node element = parser.getNodeById("03");
String type = element.valueOf("@type");
assertEquals("android", type);
}
@Test
public void getElementsListByTitleTest() {
parser = new Dom4JParser(new File(fileName));
Node element = parser.getElementsListByTitle("XML");
assertEquals("java", element.valueOf("@type"));
assertEquals("02", element.valueOf("@tutId"));
assertEquals("XML", element.selectSingleNode("title").getText());
assertEquals("title", element.selectSingleNode("title").getName());
}
@Test
public void generateModifiedDocumentTest() {
parser = new Dom4JParser(new File(fileName));
parser.generateModifiedDocument();
File generatedFile = new File("src/test/resources/example_dom4j_updated.xml");
assertTrue(generatedFile.exists());
parser.setFile(generatedFile);
Node element = parser.getNodeById("02");
assertEquals("XML updated", element.selectSingleNode("title").getText());
}
@Test
public void generateNewDocumentTest() {
parser = new Dom4JParser(new File(fileName));
parser.generateNewDocument();
File newFile = new File("src/test/resources/example_dom4j_new.xml");
assertTrue(newFile.exists());
parser.setFile(newFile);
Node element = parser.getNodeById("01");
assertEquals("XML with Dom4J", element.selectSingleNode("title").getText());
}
}
+38
View File
@@ -0,0 +1,38 @@
package com.baeldung.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import org.jdom2.Element;
import org.junit.Test;
public class JDomParserUnitTest {
final String fileName = "src/test/resources/example_jdom.xml";
JDomParser parser;
@Test
public void getFirstElementListTest() {
parser = new JDomParser(new File(fileName));
List<Element> firstList = parser.getAllTitles();
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).getAttributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new JDomParser(new File(fileName));
Element el = parser.getNodeById("03");
String type = el.getAttributeValue("type");
assertEquals("android", type);
}
}
+42
View File
@@ -0,0 +1,42 @@
package com.baeldung.xml;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Test;
import com.baeldung.xml.binding.Tutorials;
public class JaxbParserUnitTest {
final String fileName = "src/test/resources/example_jaxb.xml";
JaxbParser parser;
@Test
public void getFullDocumentTest() {
parser = new JaxbParser(new File(fileName));
Tutorials tutorials = parser.getFullDocument();
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 4);
assertTrue(tutorials.getTutorial().get(0).getType().equalsIgnoreCase("java"));
}
@Test
public void createNewDocumentTest() {
File newFile = new File("src/test/resources/example_jaxb_new.xml");
parser = new JaxbParser(newFile);
parser.createNewDocument();
assertTrue(newFile.exists());
Tutorials tutorials = parser.getFullDocument();
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 1);
assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb"));
}
}
+25
View File
@@ -0,0 +1,25 @@
package com.baeldung.xml;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import org.junit.Test;
public class JaxenDemoUnitTest {
final String fileName = "src/test/resources/example_jaxen.xml";
JaxenDemo jaxenDemo;
@Test
public void getFirstLevelNodeListTest() {
jaxenDemo = new JaxenDemo(new File(fileName));
List<?> list = jaxenDemo.getAllTutorial();
assertNotNull(list);
assertTrue(list.size() == 4);
}
}
+28
View File
@@ -0,0 +1,28 @@
package com.baeldung.xml;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import org.junit.Test;
import com.baeldung.xml.binding.Tutorial;
public class StaxParserUnitTest {
final String fileName = "src/test/resources/example_stax.xml";
StaxParser parser;
@Test
public void getAllTutorialsTest() {
parser = new StaxParser(new File(fileName));
List<Tutorial> tutorials = parser.getAllTutorial();
assertNotNull(tutorials);
assertTrue(tutorials.size() == 4);
assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java"));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.xml;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
public class XMLDocumentWriterUnitTest {
@Test
public void givenXMLDocumentWhenWriteIsCalledThenXMLIsWrittenToFile() throws Exception {
Document document = createSampleDocument();
new XMLDocumentWriter().write(document, "company_simple.xml", false, false);
}
@Test
public void givenXMLDocumentWhenWriteIsCalledWithPrettyPrintThenFormattedXMLIsWrittenToFile() throws Exception {
Document document = createSampleDocument();
new XMLDocumentWriter().write(document, "company_prettyprinted.xml", false, true);
}
private Document createSampleDocument() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element companyElement = document.createElement("Company");
document.appendChild(companyElement);
Element departmentElement = document.createElement("Department");
departmentElement.setAttribute("name", "Sales");
companyElement.appendChild(departmentElement);
Element employee1 = document.createElement("Employee");
employee1.setAttribute("name", "John Smith");
departmentElement.appendChild(employee1);
Element employee2 = document.createElement("Employee");
employee2.setAttribute("name", "Tim Dellor");
departmentElement.appendChild(employee2);
return document;
}
@After
public void cleanUp() throws Exception {
FileUtils.deleteQuietly(new File("company_simple.xml"));
FileUtils.deleteQuietly(new File("company_prettyprinted.xml"));
}
}
@@ -0,0 +1,139 @@
package com.baeldung.xml;
import static org.junit.Assert.assertEquals;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XercesDomUnitTest {
final private String FILE_NAME = "src/test/resources/example_jdom.xml";
final private String OUTPUT_DOM = "src/test/resources/Xerces_dom.xml";
private Document doc;
private DocumentBuilder builder;
@Before
public void loadXmlFile() throws Exception {
if (doc == null) {
builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
doc = builder.parse(new File(FILE_NAME));
doc.getDocumentElement()
.normalize();
}
}
@Test
public void whenGetElementByTag_thenSuccess() {
NodeList nodeList = doc.getElementsByTagName("tutorial");
Node first = nodeList.item(0);
assertEquals(4, nodeList.getLength());
assertEquals(Node.ELEMENT_NODE, first.getNodeType());
assertEquals("tutorial", first.getNodeName());
}
@Test
public void whenGetFirstElementAttributes_thenSuccess() {
Node first = doc.getElementsByTagName("tutorial")
.item(0);
NamedNodeMap attrList = first.getAttributes();
assertEquals(2, attrList.getLength());
assertEquals("tutId", attrList.item(0)
.getNodeName());
assertEquals("01", attrList.item(0)
.getNodeValue());
assertEquals("type", attrList.item(1)
.getNodeName());
assertEquals("java", attrList.item(1)
.getNodeValue());
}
@Test
public void whenTraverseChildNodes_thenSuccess() {
Node first = doc.getElementsByTagName("tutorial")
.item(0);
NodeList nodeList = first.getChildNodes();
int n = nodeList.getLength();
Node current;
for (int i = 0; i < n; i++) {
current = nodeList.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(current.getNodeName() + ": " + current.getTextContent());
}
}
}
@Test
public void whenModifyElementAttribute_thenModified() {
NodeList nodeList = doc.getElementsByTagName("tutorial");
Element first = (Element) nodeList.item(0);
assertEquals("java", first.getAttribute("type"));
first.setAttribute("type", "other");
assertEquals("other", first.getAttribute("type"));
}
@Test
public void whenCreateNewDocument_thenCreated() throws Exception {
Document newDoc = builder.newDocument();
Element root = newDoc.createElement("users");
newDoc.appendChild(root);
Element first = newDoc.createElement("user");
root.appendChild(first);
first.setAttribute("id", "1");
Element email = newDoc.createElement("email");
email.appendChild(newDoc.createTextNode("john@example.com"));
first.appendChild(email);
assertEquals(1, newDoc.getChildNodes()
.getLength());
assertEquals("users", newDoc.getChildNodes()
.item(0)
.getNodeName());
printDom(newDoc);
saveDomToFile(newDoc, OUTPUT_DOM);
}
private void printDom(Document document) throws Exception {
DOMSource dom = new DOMSource(document);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.transform(dom, new StreamResult(System.out));
}
private void saveDomToFile(Document document, String fileName) throws Exception {
DOMSource dom = new DOMSource(document);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
StreamResult result = new StreamResult(new File(fileName));
transformer.transform(dom, result);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.xml.attribute;
import org.dom4j.DocumentException;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.xmlunit.assertj.XmlAssert.assertThat;
/**
* Unit test for {@link Dom4jTransformer}.
*/
public class Dom4jProcessorUnitTest {
@Test
public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws TransformerFactoryConfigurationError, TransformerException, DocumentException, SAXException {
String path = getClass().getResource("/xml/attribute.xml")
.toString();
Dom4jTransformer transformer = new Dom4jTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
String result = transformer.modifyAttribute(attribute, oldValue, newValue);
assertThat(result).hasXPath("//*[contains(@customer, 'false')]");
}
@Test
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException, SAXException {
String path = getClass().getResource("/xml/attribute.xml")
.toString();
Dom4jTransformer transformer = new Dom4jTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
.toURI()))));
String result = transformer
.modifyAttribute(attribute, oldValue, newValue)
.replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11
assertThat(result).and(expectedXml)
.areSimilar();
}
@Test
public void givenXmlXee_whenInit_thenThrowException() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
String path = getClass().getResource("/xml/xee_attribute.xml")
.toString();
assertThatThrownBy(() -> {
new Dom4jTransformer(path);
}).isInstanceOf(DocumentException.class);
}
}
@@ -0,0 +1,48 @@
package com.baeldung.xml.attribute;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.xmlunit.assertj.XmlAssert.assertThat;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.xpath.XPathExpressionException;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Unit test for {@link JaxpTransformer}.
*/
public class JaxpProcessorUnitTest {
@Test
public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
String path = getClass().getResource("/xml/attribute.xml")
.toString();
JaxpTransformer transformer = new JaxpTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
String result = transformer.modifyAttribute(attribute, oldValue, newValue);
assertThat(result).hasXPath("//*[contains(@customer, 'false')]");
}
@Test
public void givenXmlXee_whenInit_thenThrowException() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
String path = getClass().getResource("/xml/xee_attribute.xml")
.toString();
assertThatThrownBy(() -> {
new JaxpTransformer(path);
}).isInstanceOf(SAXParseException.class);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.xml.attribute;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.xmlunit.assertj.XmlAssert.assertThat;
/**
* Unit test for {@link JooxTransformer}.
*/
public class JooxProcessorUnitTest {
@Test
public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, TransformerFactoryConfigurationError {
String path = getClass().getResource("/xml/attribute.xml")
.toString();
JooxTransformer transformer = new JooxTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
String result = transformer.modifyAttribute(attribute, oldValue, newValue);
assertThat(result).hasXPath("//*[contains(@customer, 'false')]");
}
@Test
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, URISyntaxException, SAXException {
String path = getClass().getResource("/xml/attribute.xml")
.toString();
JooxTransformer transformer = new JooxTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
.toURI()))));
String result = transformer
.modifyAttribute(attribute, oldValue, newValue)
.replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11
assertThat(result).and(expectedXml)
.areSimilar();
}
@Test
public void givenXmlXee_whenInit_thenThrowException() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
String path = getClass().getResource("/xml/xee_attribute.xml")
.toString();
assertThatThrownBy(() -> {
new JooxTransformer(path);
}).isInstanceOf(SAXParseException.class);
}
}
@@ -0,0 +1,52 @@
package com.baeldung.xml.jibx;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.InputStream;
import static junit.framework.Assert.assertEquals;
public class CustomerUnitTest {
@Test
public void whenUnmarshalXML_ThenFieldsAreMapped() throws JiBXException, FileNotFoundException {
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("Customer1.xml");
Customer customer = (Customer) uctx.unmarshalDocument(inputStream, null);
assertEquals("Stefan Jaeger", customer.getPerson().getName());
assertEquals("Davos Dorf", customer.getCity());
}
@Test
public void WhenUnmarshal_ThenMappingInherited() throws JiBXException, FileNotFoundException {
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("Customer1.xml");
Customer customer = (Customer) uctx.unmarshalDocument(inputStream, null);
assertEquals(12345, customer.getPerson().getCustomerId());
}
@Test
public void WhenUnmarshal_ThenPhoneMappingRead() throws JiBXException, FileNotFoundException {
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("Customer1.xml");
Customer customer = (Customer) uctx.unmarshalDocument(inputStream, null);
assertEquals("234678", customer.getHomePhone().getNumber());
}
}
@@ -0,0 +1,31 @@
package com.baeldung.xml.stax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
public class StaxParserUnitTest {
@Test
public void givenWebsitesXML_whenParsed_thenNotNull() {
List<WebSite> websites = StaxParser.parse("src/test/resources/xml/websites.xml");
assertNotNull(websites);
}
@Test
public void givenWebsitesXML_whenParsed_thenSizeIsThree() {
List<WebSite> websites = StaxParser.parse("src/test/resources/xml/websites.xml");
assertEquals(3, websites.size());
}
@Test
public void givenWebsitesXML_whenParsed_thenLocalhostExists() {
List<WebSite> websites = StaxParser.parse("src/test/resources/xml/websites.xml");
assertEquals("Localhost", websites.get(2).getName());
}
}
@@ -0,0 +1,32 @@
package com.baeldung.xmlhtml.freemarker;
import com.baeldung.xmlhtml.stax.StaxTransformer;
import freemarker.template.TemplateException;
import org.junit.jupiter.api.Test;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
public class FreemarkerTransformerUnitTest {
@Test
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException, TemplateException {
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
.getResource("/xmlhtml/notification.html")
.toURI()))));
StaxTransformer staxTransformer = new StaxTransformer("src/test/resources/xmlhtml/notification.xml");
String templateFile = "freemarker.html";
String templateDirectory = "src/test/resources/templates";
FreemarkerTransformer transformer = new FreemarkerTransformer(staxTransformer, templateDirectory, templateFile);
String result = transformer.html();
assertThat(result).isEqualTo(expectedHtml);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.xmlhtml.jaxp;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
public class JaxpTransformerUnitTest {
@Test
public void givenXml_whenTransform_thenGetHtml() throws IOException, SAXException, ParserConfigurationException, TransformerException, URISyntaxException {
String path = getClass()
.getResource("/xmlhtml/notification.xml")
.toString();
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
.getResource("/xmlhtml/notification.html")
.toURI()))));
JaxpTransformer transformer = new JaxpTransformer(path);
String result = transformer
.html()
.replaceAll("(?m)^\\s+", "");//Delete extra spaces added by Java 11
assertThat(result).isEqualTo(expectedHtml);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.xmlhtml.mustache;
import com.baeldung.xmlhtml.stax.StaxTransformer;
import org.junit.jupiter.api.Test;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
public class MustacheTransformerUnitTest {
@Test
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException {
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
.getResource("/xmlhtml/notification.html")
.toURI()))));
StaxTransformer staxTransformer = new StaxTransformer("src/test/resources/xmlhtml/notification.xml");
String templateFile = "src/test/resources/templates/template.mustache";
MustacheTransformer transformer = new MustacheTransformer(staxTransformer, templateFile);
String result = transformer.html();
assertThat(result).isEqualTo(expectedHtml);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.xmlhtml.stax;
import org.junit.jupiter.api.Test;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
public class StaxTransformerUnitTest {
@Test
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException {
String path = "src/test/resources/xmlhtml/notification.xml";
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
.getResource("/xmlhtml/notification.html")
.toURI()))));
StaxTransformer transformer = new StaxTransformer(path);
String result = transformer.html();
assertThat(result).isEqualTo(expectedHtml);
}
}