为什么在 IntelliJ "Run" 中写入此测试中的流有效,但在我使用 Maven "test" 时却无效?

Why does writing to the stream in this test work in IntelliJ's "Run", but not when I use Maven "test"?

在我的应用程序中,我遇到一个问题,当我 运行 "mvn clean test" 时 OutputStream 没有向文件写入任何内容,但是当我 运行 它在IntelliJ 通过右键单击 运行 testWritingToFile(),它工作正常并输出到文件。

我有以下测试:

@Test
public void testWritingToFile() throws Exception {
    File fileXml = new File("xmltest.xml");
    OutputStream outputStream = new FileOutputStream(fileXml);
    XmlStreamWriting xmlStreamWriting = new XmlStreamWriting(outputStream);

    xmlStreamWriting.writeXmlToStream();

    outputStream.close();

}

这是我从测试 (XmlStreamWriting.java) 调用的 class:

public class XmlStreamWriting extends XmlStreamWritingBase {
    public XmlStreamWriting(OutputStream outputStream) {
        this.setOutputStream(outputStream);
    }

    public void writeXmlToStream() throws XMLStreamException {
        XMLStreamWriter xmlStreamWriter = this.getXmlStreamWriter();
        xmlStreamWriter.writeStartElement("test");
        xmlStreamWriter.writeCharacters("This is a test.");
        xmlStreamWriter.writeEndElement(); //test
    }
}

这里是摘要 class 它扩展了 (XmlStreamWritingBase.java):

public abstract class XmlStreamWritingBase {
    private XMLStreamWriter xmlStreamWriterPrivate;
    private OutputStream outputStream;

    public XMLStreamWriter getXmlStreamWriter() throws XMLStreamException {
        if(xmlStreamWriterPrivate == null) {
            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
            xmlStreamWriterPrivate = xmlOutputFactory.createXMLStreamWriter(this.getOutputStream());
        }
        return this.xmlStreamWriterPrivate;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
}

如果重要的话,我正在使用 jrockit jdk 1.6.0_29。 IntelliJ 和 Maven 都设置为 运行 即 JDK.

我是否必须将 OutputStream 直接传递给每个方法?为什么 writeXmlToStream() 方法不起作用?

编辑:同样只是为了验证流在这两种情况下都有效,我将测试更改为此,当我从 Maven 运行 时,Test1 和 Test2 之间没有内容,但是当我 运行 使用 IntelliJ,xml 出现在两个字符串之间:

public void testWritingToFile() throws Exception {
    File fileXml = new File("xmltest.xml");
    OutputStream outputStream = new FileOutputStream(fileXml);

    outputStream.write("Test1".getBytes());

    XmlStreamWriting xmlStreamWriting = new XmlStreamWriting(outputStream);

    xmlStreamWriting.writeXmlToStream();

    outputStream.write("Test2".getBytes());

    outputStream.close();
}

maven 的输出是“Test1Test2”,IntelliJ "Run" 的输出是“Test1<test>This is a test.</test>Test2

解决方法是我没有设置编码类型。或者他们在某种程度上有所不同。当我将编码设置为 UTF-8 时,文件写入就好了:

xmlOutputFactory.createXMLStreamWriter(this.getOutputStream(), "UTF-8");

我发现这个是因为当我在 IntelliJ 中设置一个 maven 目标时,开关 -Dfile.encoding=UTF-8 将附加到 mvn 命令的末尾,然后测试将正确构建 XML 文件。