[英]How to unit test - zipping a file
我编写了一个简单的方法,它接收一个文件夹的路径,压缩该文件夹中的所有内容,并将其保存到指定的目标路径。
void zipFiles(string sourcePath, string destinationPath, string nameToZipAs)
{
try
{
// This is where the zip file will be saved.
string fullDestinationPath = $"{destinationPath}\\{nameToZipAs}";
ZipFile.CreateFromDirectory(sourcePath, fullDestinationPath);
}
catch (Exception e)
{
// ...
}
}
我想知道我将如何进行单元测试。 我读到单元测试不应该触及文件系统。 这是正确的良好做法吗? 如果是这样,那么我无法在单元测试中(以编程方式)创建文件夹,以便使用我的方法压缩该文件夹以验证它是否有效。
如果正确隔离被测代码,您可以对代码调用ZipFile.CreateFromDirectory(...)
方法和某些特定参数的事实进行单元测试。 如果您有 VS Enterprise,则可以使用MS Fakes 。 下面的代码显示了一个示例 NUnit 测试(dotnet core 3.1),为 System.IO.Compression.ZipFile 添加了 Fakes Assembly):
[Test]
public void ZipFiles_CallsZipFileCreateFromDirectoryWithCorrectArguments()
{
string sourceDirectoryName = null;
string destinationArchiveFileName = null;
using (ShimsContext.Create())
{
System.IO.Compression.Fakes.ShimZipFile.CreateFromDirectoryStringString = (arg0, arg1) => {
sourceDirectoryName = arg0;
destinationArchiveFileName = arg1;
};
zipFiles("source", "dest", "zipname");
}
Assert.Multiple(() => {
Assert.AreEqual("source", sourceDirectoryName);
Assert.AreEqual("dest\\zipname", destinationArchiveFileName);
});
}
单元测试项目中的Fakes\\System.IO.Compression.ZipFile.fakes
文件应如下所示:
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
<Assembly Name="System.IO.Compression.ZipFile" Version="4.0.5.0"/>
</Fakes>
最后一个我强烈推荐的链接: Unit testing best practice with .NET Core and .NET Standard
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.