如何对 XML 文档到字符串转换方法进行单元测试

问题描述 投票:0回答:1
public static String convertDocumentToString(Document xmlDocument) {

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            StringWriter writer = new StringWriter();

            transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));

            return writer.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

我正在尝试对以下方法进行单元测试(junit) 在单元测试中创建文档的最简单/最简单的方法是什么?

有什么建议吗? Mockito 在这里不可行

例如测试

1. @Test
1. public void convertDocumentToString() {
1. Document document = ??
1. 
1. class.convertDocumentToString(document)

我如何构建一个文档变量来传递给该方法

java dom junit
1个回答
0
投票

您可以使用

DocumentBuilder
创建简单的 XML 文档:

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MyTest {

    @Test
    public void myTest() throws Exception {
        Document xmlDocument = createDocument();

        String result = new MyTransformer().convertDocumentToString(xmlDocument);

        String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><root><element>value</element></root>";

        assertEquals(expected, result);
    }

    private Document createDocument() throws Exception {

        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .newDocument();

        // Create root element
        Element rootElement = document.createElement("root");
        document.appendChild(rootElement);

        // Create child element
        Element childElement = document.createElement("element");
        childElement.appendChild(document.createTextNode("value"));

        rootElement.appendChild(childElement);

        return document;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.