使用 dotnet test 與 xUnit 為 .NET 中的 C# 進行單元測試

本教學課程示範如何建置包含單元測試專案和原始程式碼專案的方案。 若要使用預先建置的解決方案來依照教學課程操作,請檢視或下載範例程式碼。 如需下載指示,請參閱範例和教學課程

建立解決方案

在本節中,會建立包含來源和測試專案的解決方案。 完成的解決方案具有下列目錄結構:

/unit-testing-using-dotnet-test
    unit-testing-using-dotnet-test.sln
    /PrimeService
        PrimeService.cs
        PrimeService.csproj
    /PrimeService.Tests
        PrimeService_IsPrimeShould.cs
        PrimeServiceTests.csproj

下列指示提供建立測試解決方案的步驟。 如需透過單一步驟建立測試解決方案的指示,請參閱建立測試解決方案的命令

  • 開啟 Shell 視窗。

  • 執行以下命令:

    dotnet new sln -o unit-testing-using-dotnet-test
    

    dotnet new sln 命令會在 unit-testing-using-dotnet-test 目錄中建立新的解決方案。

  • 將目錄變更為 unit-testing-using-dotnet-test 資料夾。

  • 執行以下命令:

    dotnet new classlib -o PrimeService
    

    dotnet new classlib 命令會在 PrimeService 資料夾中建立新的類別庫專案。 新的類別庫會包含要測試的程式碼。

  • Class1.cs 重新命名為 PrimeService.cs

  • 用下列程式碼取代 PrimeService.cs 中的程式碼:

    using System;
    
    namespace Prime.Services
    {
        public class PrimeService
        {
            public bool IsPrime(int candidate)
            {
                throw new NotImplementedException("Not implemented.");
            }
        }
    }
    
  • 上述 程式碼:

  • unit-testing-using-dotnet-test 目錄中,執行下列命令,將類別庫專案新增至解決方案:

    dotnet sln add ./PrimeService/PrimeService.csproj
    
  • 執行下列命令來建立 PrimeService.Tests 專案:

    dotnet new xunit -o PrimeService.Tests
    
  • 上述命令會:

    • PrimeService.Tests 目錄中建立 PrimeService.Tests 專案。 測試專案會使用 xUnit 作為測試程式庫。
    • 將下列 <PackageReference /> 元素新增至專案檔,以設定測試執行器:
      • Microsoft.NET.Test.Sdk
      • xunit
      • xunit.runner.visualstudio
      • coverlet.collector
  • 執行下列命令,將測試專案新增至解決方案檔:

    dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj
    
  • PrimeService 類別庫新增為 PrimeService.Tests 專案的相依性:

    dotnet add ./PrimeService.Tests/PrimeService.Tests.csproj reference ./PrimeService/PrimeService.csproj  
    

用於建立解決方案的命令

本節摘要說明上一節中的所有命令。 如果您已完成上一節中的步驟,請略過本節。

下列命令會在 Windows 機器上建立測試解決方案。 針對 macOS 和 Unix,將 ren 命令更新為 ren 的 OS 版本,以重新命名檔案:

dotnet new sln -o unit-testing-using-dotnet-test
cd unit-testing-using-dotnet-test
dotnet new classlib -o PrimeService
ren .\PrimeService\Class1.cs PrimeService.cs
dotnet sln add ./PrimeService/PrimeService.csproj
dotnet new xunit -o PrimeService.Tests
dotnet add ./PrimeService.Tests/PrimeService.Tests.csproj reference ./PrimeService/PrimeService.csproj
dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj

依照上一節中的「用下列程式碼取代 PrimeService.cs 中的程式碼」的指示操作。

建立測試

在測試驅動開發 (TDD) 中常用的方法是先撰寫一個 (失敗) 測試,再實作目標程式碼。 本教學課程使用 TDD 做法。 方法 IsPrime 可呼叫,但無法實作。 測試呼叫 IsPrime 失敗。 使用 TDD 時,會撰寫已知失敗的測試。 目標程式碼會更新以讓測試通過。 請重複此做法,撰寫失敗的測試,然後更新目標程式碼以通過。

更新 PrimeService.Tests 專案:

  • 刪除 PrimeService.Tests/UnitTest1.cs
  • 建立 PrimeService.Tests/PrimeService_IsPrimeShould.cs 檔案。
  • 用下列程式碼取代 PrimeService_IsPrimeShould.cs 中的程式碼:
using Xunit;
using Prime.Services;

namespace Prime.UnitTests.Services
{
    public class PrimeService_IsPrimeShould
    {
        [Fact]
        public void IsPrime_InputIs1_ReturnFalse()
        {
            var primeService = new PrimeService();
            bool result = primeService.IsPrime(1);

            Assert.False(result, "1 should not be prime");
        }
    }
}

[Fact] 屬性宣告測試執行器執行的測試方法。 從 PrimeService.Tests 資料夾執行 dotnet testdotnet test 命令會建置專案並執行測試。 xUnit 測試執行器包含執行測試的程式進入點。 dotnet test 會使用單元測試專案來啟動測試執行器。

測試失敗,因為 IsPrime 尚未實作。 使用 TDD 做法,只撰寫足夠的程式碼以讓此測試通過。 以下列程式碼來更新 IsPrime

public bool IsPrime(int candidate)
{
    if (candidate == 1)
    {
        return false;
    }
    throw new NotImplementedException("Not fully implemented.");
}

執行 dotnet test。 測試會成功。

新增更多測試

新增 0 和 -1 的質數測試。 您可以複製在上一個步驟中建立的測試,並製作下列程式碼複本以測試 0 和 -1。 但請不要這樣做,因為有個更好的方法。

var primeService = new PrimeService();
bool result = primeService.IsPrime(1);

Assert.False(result, "1 should not be prime");

只在參數變更會導致程式碼重複和測試膨脹時,才複製測試程式碼。 下列 xUnit 屬性可讓您撰寫一套類似的測試:

  • [Theory] 代表執行相同程式碼但具有不同輸入引數的測試套件。
  • [InlineData] 屬性會指定這些輸入的值。

不要建立新的測試,而是套用上述 xUnit 屬性來建立單一理論。 取代下列程式碼:

[Fact]
public void IsPrime_InputIs1_ReturnFalse()
{
    var primeService = new PrimeService();
    bool result = primeService.IsPrime(1);

    Assert.False(result, "1 should not be prime");
}

使用下列程式碼:

[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void IsPrime_ValuesLessThan2_ReturnFalse(int value)
{
    var result = _primeService.IsPrime(value);

    Assert.False(result, $"{value} should not be prime");
}

在上述程式碼中,[Theory][InlineData] 可用來測試小於二的多個值。 兩是最小的質數。

在類別宣告後和 [Theory] 屬性前新增下列程式碼:

private readonly PrimeService _primeService;

public PrimeService_IsPrimeShould()
{
    _primeService = new PrimeService();
}

執行 dotnet test,然後會有兩個測試失敗。 若要讓所有測試都通過,請使用下列程式碼更新 IsPrime 方法:

public bool IsPrime(int candidate)
{
    if (candidate < 2)
    {
        return false;
    }
    throw new NotImplementedException("Not fully implemented.");
}

依照 TDD 做法操作,新增更多失敗的測試,然後更新目標程式碼。 請參閱測試的完成版程式庫的完整實作

完成的 IsPrime 方法不是測試質數的有效演算法。

其他資源