单元测试Xml编码问题

本文关键字:问题 编码 Xml 单元测试 | 更新日期: 2023-09-27 18:08:22

考虑以下类:

public class SampleXmlGenerator
{
    public byte[] GenerateDocumentBytes()
    {
        byte[] fileBytes;
        using (var xmlStream = new MemoryStream())
        {
            using (var myWriter = new XmlTextWriter(xmlStream, Encoding.GetEncoding("UTF-8")))
            {
                myWriter.Formatting = Formatting.Indented;
                myWriter.Indentation = 4;
                myWriter.IndentChar = ' ';
                myWriter.WriteStartDocument();
                myWriter.WriteStartElement("foo");
                myWriter.WriteString("bar");
                myWriter.WriteEndElement(); // end foo
                myWriter.Flush();
                fileBytes = xmlStream.ToArray();
            }
        }
        return fileBytes;
    }
}

使用下面的单元测试:

[TestClass]
public class TestSampleXmlGenerator
{
    [TestMethod]
    public void TextEmptyDocument()
    {
        var actualBytes = new SampleXmlGenerator().GenerateDocumentBytes();
        var actualUtf8String = Encoding.UTF8.GetString(actualBytes);
        Console.Out.WriteLine("// actualUtf8String");
        Console.Out.WriteLine(actualUtf8String);
        var actualDefaultString = Encoding.Default.GetString(actualBytes);
        Console.Out.WriteLine("// actualDefaultString");
        Console.Out.WriteLine(actualDefaultString);

        var expectedString = @"<?xml version=""1.0"" encoding=""utf-8""?>
<foo>bar</foo>";
        var expectedBytes = Encoding.UTF8.GetBytes(expectedString);
//      var expectedBytes = Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(@"<?xml version=""1.0"" encoding=""utf-8""?>
//<foo>bar</foo>"));
//      var expectedString = Encoding.UTF8.GetString(expectedBytes);
        Console.Out.WriteLine("// expectedString");
        Console.Out.WriteLine(expectedString);
        Assert.AreEqual(expectedBytes.Length, actualBytes.Length);
        //Assert.AreEqual(expectedString, actualUtf8String);
    }
}

最后输出:

Assert.AreEqual failed. Expected:<54>. Actual:<57>. 
// actualUtf8String
<?xml version="1.0" encoding="utf-8"?>
<foo>bar</foo>
// actualDefaultString
<?xml version="1.0" encoding="utf-8"?>
<foo>bar</foo>
// expectedString
<?xml version="1.0" encoding="utf-8"?>
<foo>bar</foo>

expectedStringactualUtf8String看起来一样,但不是。

actualDefaultString显示开头额外的3个字符。

怎么了?如何测试/比较生成的XML?我应该怎么做?

单元测试Xml编码问题

您所看到的是BOM序言

https://msdn.microsoft.com/en-us/library/system.text.encoding.getpreamble (v = vs.110) . aspx

你可以测试它,或者不序列化它

根据Martin和Keith的建议,以及一些额外的研究,我最终以以下方式(基于以下SO文章)从单元测试中生成的XML字节中删除了BOM:

        var xmlBytes = new SampleXmlGenerator().GenerateDocumentBytes();
        var newXmlDoc = new XmlDocument {PreserveWhitespace = true};
        newXmlDoc.Load(new MemoryStream(xmlBytes));
        var actualBytes = Encoding.UTF8.GetBytes(newXmlDoc.OuterXml);

现在单元测试通过了!