Skip to main content
 首页 » 编程设计

C# 单元测试,使用 zip 文件中的 XML

2024年02月23日15kevingrace

我有一个类接受一个字符串作为 xml 文件的路径并输出一个对象。我想使用 NUnit 和一些预先生成的测试脚本来测试这个类。

我将脚本放在一个 zip 文件中并包含在项目中。我想做这样的事情:

// Not sure how to do this 
List<byte[]> scripts = GetTheScriptsSomehow(); 
 
foreach(var script in scripts ) 
{ 
  var parsedScript = ScriptParser.Parse(script); 
  Assert.AreEqual(parsedScript.Blah, "BLAH"); 
} 

我最关心的部分是如何访问压缩的脚本和项目的一部分。

谢谢!

编辑:为了解决一些评论,zip 文件是单元测试项目的一部分,而不是已发布的代码库。它包含应产生可测试的已知输出的测试脚本。它们被压缩是因为脚本相当大(每个 100mb)

请您参考如下方法:

在资源(项目属性/资源/添加资源/添加现有文件)中添加此zip文件,并使用SharpZipLib从zip中提取它,假设您的zip文件是

scripts.zip

提取字符串中脚本的代码:

ZipInputStream zip = new ZipInputStream(new MemoryStream(Properties.Resources.scripts)); 
while (zip.GetNextEntry() != null) 
{ 
  MemoryStream data = new MemoryStream(); 
  zip.CopyTo(data); 
  data.Position = 0; 
  string scriptContents = new StreamReader(data).ReadToEnd(); 
  /// do something with scriptContents variable 
} 

以下是 SharpZipLib 用法的一些示例:

http://wiki.sharpdevelop.net/SharpZipLib-Zip-Samples.ashx