使用 NUnit 和 .NET Core 對 C# 進行單元測試

本教學課程會引導您逐步進行建置範例方案的互動式體驗,以了解單元測試概念。 如果您想要使用預先建置的方案進行教學課程,請在開始之前檢視或下載範例程式碼。 如需下載指示,請參閱範例和教學課程

本文旨在說明如何測試 .NET Core 專案。 如果您要測試 ASP.NET Core 專案,請參閱 ASP.NET Core 中的整合測試 (部分機器翻譯)。

必要條件

  • .NET 8.0 或更新版本。
  • 您偏好的文字編輯器或程式碼編輯器。

建立來源專案

開啟 Shell 視窗。 建立名稱為 unit-testing-using-nunit 的目錄來放置解決方案。 在此新目錄中,執行下列命令以針對類別庫與測試專案建立新方案檔:

dotnet new sln

接著,建立 PrimeService 目錄。 下列大綱顯示到目前為止的目錄與檔案結構:

/unit-testing-using-nunit
    unit-testing-using-nunit.sln
    /PrimeService

PrimeService 設為目前的目錄,然後執行下列命令以建立來源專案:

dotnet new classlib

Class1.cs 重新命名為 PrimeService.cs。 建立會失敗的 PrimeService 類別實作:

using System;

namespace Prime.Services
{
    public class PrimeService
    {
        public bool IsPrime(int candidate)
        {
            throw new NotImplementedException("Please create a test first.");
        }
    }
}

將目錄變更回 unit-testing-using-nunit 目錄。 執行下列命令,將類別庫專案新增至方案:

dotnet sln add PrimeService/PrimeService.csproj

建立測試專案

接著,建立 PrimeService.Tests 目錄。 下列大綱顯示目錄結構:

/unit-testing-using-nunit
    unit-testing-using-nunit.sln
    /PrimeService
        Source Files
        PrimeService.csproj
    /PrimeService.Tests

PrimeService.Tests 目錄設為目前的目錄,然後使用下列命令建立新的專案:

dotnet new nunit

dotnet new 命令會建立將 NUnit 用作測試程式庫的測試專案。 產生的範本會在 PrimeService.Tests.csproj 檔案中設定測試執行器:

<ItemGroup>
  <PackageReference Include="nunit" Version="4.1.0" />
  <PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
  <PackageReference Include="NUnit.Analyzers" Version="4.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
  </PackageReference>
</ItemGroup>

注意

在 .NET 9 之前,產生的程式碼可能會參考舊版的 NUnit 測試架構。 您可以使用 dotnet CLI 來更新套件。 或者,開啟 PrimeService.Tests.csproj 檔案,並將套件參考項目群組的內容取代為上面的程式碼。

測試專案需要其他套件來建立和執行單元測試。 上一個步驟中的 dotnet new 命令新增了 Microsoft 測試 SDK、NUnit 測試架構以及 NUnit 測試配接器。 現在,將 PrimeService 類別庫新增為專案的另一個相依性。 使用 dotnet add reference 命令:

dotnet add reference ../PrimeService/PrimeService.csproj

您可以在 GitHub 的範例存放庫中看到完整檔案。

下列大綱顯示最終方案配置:

/unit-testing-using-nunit
    unit-testing-using-nunit.sln
    /PrimeService
        Source Files
        PrimeService.csproj
    /PrimeService.Tests
        Test Source Files
        PrimeService.Tests.csproj

unit-testing-using-nunit 目錄中執行下列命令:

dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj

建立第一個測試

請撰寫一個失敗的測試,再使其通過,然後重複此流程。 在 PrimeService.Tests 目錄中,將 UnitTest1.cs 檔案重新命名為 PrimeService_IsPrimeShould.cs,並將其整個內容取代為下列程式碼:

using NUnit.Framework;
using Prime.Services;

namespace Prime.UnitTests.Services
{
    [TestFixture]
    public class PrimeService_IsPrimeShould
    {
        private PrimeService _primeService;

        [SetUp]
        public void SetUp()
        {
            _primeService = new PrimeService();
        }

        [Test]
        public void IsPrime_InputIs1_ReturnFalse()
        {
            var result = _primeService.IsPrime(1);

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

[TestFixture] 屬性代表包含單元測試的類別。 [Test] 屬性指出方法是測試方法。

儲存此檔案,並執行 dotnet test 命令以建置測試和類別庫,再執行測試。 NUnit 測試執行器包含執行測試的程式進入點。 dotnet test 會使用您建立的單元測試專案來開始測試執行器。

您的測試失敗。 您尚未建立實作。 在可運作的 PrimeService 類別中撰寫最簡單的程式碼,讓此測試通過:

public bool IsPrime(int candidate)
{
    if (candidate == 1)
    {
        return false;
    }
    throw new NotImplementedException("Please create a test first.");
}

unit-testing-using-nunit 目錄中,再次執行 dotnet testdotnet test 命令會依序執行 PrimeService 專案和 PrimeService.Tests 專案的建置。 建置這兩個專案後,系統會執行此單一測試。 測試通過。

新增更多功能

現在,您已經讓一個測試順利通過,您可以撰寫更多測試。 還有一些其他適用於質數 0、-1 的簡單案例。 您可以使用 [Test] 屬性來加入新測試,但很快就會單調乏味。 另有其他 NUnit 屬性可供您撰寫類似測試的套件。 [TestCase] 屬性可用於建立執行相同程式碼,但輸入引數不同的測試套件。 您可以使用 [TestCase] 屬性來指定這些輸入值。

不需要建立新的測試,只要套用此屬性來建立單一資料驅動型測試即可。 資料驅動型測試是一種測試方法,其會測試數個低於二 (最小質數) 的值:

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

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

執行 dotnet test,然後會有兩個測試失敗。 若要讓所有測試都能通過,請變更 PrimeService.cs 檔案中 Main 方法開頭處的 if 子句:

if (candidate < 2)

繼續在主要程式庫中新增更多測試、理論和程式碼,以反覆執行。 您有測試的完成版程式庫的完整實作

您已建置好小型的程式庫和該程式庫的一組單元測試, 您也建立了解決方案結構,使加入新套件與測試成為標準工作流程的一部分。 您已集中大部分的時間與精力以解決應用程式目標。