我有一个测试类,它测试两个生成的xml文件是否与已经生成的已知良好的xml文件匹配。比较写入磁盘的文件时,测试通过。当将仍在内存中的文件与从磁盘读取的已知良好文件进行比较时,它会失败,因为预期的流要长17字节。
测试等级
[TestFixture]
class XmlExporterTest
{
private const string ExpectedXMLFile = @"....ProjectsEXPECTED FILE.xml";
private XmlExporter xmlExporter;
[SetUp]
public void SetUp()
{
// clean up from before, since we might want the info after the tests (if they fail for example)
string[] filePaths = Directory.GetFiles(@"....tmp");
foreach (string f in filePaths)
{
File.Delete(f);
}
}
// this always fails because the stream length is 17 bytes short
[Test]
public void TestExportToXMLStream()
{
// test write to stream
using (Stream actualStream = xmlExporter.ExportToXML(true))
{
using (Stream expectedStream = new FileStream(ExpectedXMLFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
{
FileAssert.AreEqual(expectedStream, actualStream);
}
}
}
// this always passes
[Test]
public void TestExportToXMLFile()
{
const string actualXMLFile = @"....tmpproject1.xml";
xmlExporter.ExportToXML(actualXMLFile, true);
FileAssert.AreEqual(ExpectedXMLFile, actualXMLFile);
}
}
XML导出类
public class XmlExporter
{
public void ExportToXML(string filename, bool normalizeZoom)
{
iexINSPECTIONXPERT arr = CreateSerializableObject(normalizeZoom);
//serialize to an XML file
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xxx", "http://www.example.com");
using (TextWriter tr2 = new StreamWriter(filename))
{
XmlSerializer sr2 = new XmlSerializer(typeof(Foo));
sr2.Serialize(tr2, arr, ns);
}
}
/// <summary>
/// Exports to XML only returning a MemoryStream object.
/// Note that the stream must be disposed of by the caller.
/// </summary>
/// <param name="normalizeZoom"></param>
/// <returns></returns>
public MemoryStream ExportToXML(bool normalizeZoom)
{
iexINSPECTIONXPERT arr = CreateSerializableObject(normalizeZoom);
//serialize to an XML file
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xxx", "http://www.example.com");
var stream = new MemoryStream();
XmlSerializer sr2 = new XmlSerializer(typeof(Foo));
sr2.Serialize(stream, arr, ns);
return stream;
}
}
其他类别
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.example.com", ElementName = "Foo")]
public class Foo
{
[XmlElementAttribute(Namespace = "", ElementName = "BAR")]
public BAR fi;
}
在写入文件和写入内存流时需要使用相同的编码,例如在这两种情况下都使用Encoding.Default
。
文件:
using (TextWriter tr2 = new StreamWriter(filename, false, Encoding.Default))
内存:
var memory = new MemoryStream();
var writer = new StreamWriter(memory, Encoding.Default);
sr2.Serialize(writer, arr, ns);