簡體   English   中英

如何單元測試 - 壓縮文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM