參考使用 dotnet test 與 xUnit 為 .NET Core 中的 C# 進行單元測試教學
建立解決方案
dotnet new sln -o PellokITHomTest
建立新的類別庫專案
cd PellokITHomTest
dotnet new classlib -o PellokService

將 Class1.cs 重新命名為 PellokService.cs。
PellokService.cs 中的程式碼取代為下列程式碼
using System;
namespace Pellok.Services
{
    public class PellokService
    {
        public bool IsPellok(int candidate)
        {
            if (candidate == 1)
            {
                return false;
            }
            throw new NotImplementedException("Not fully implemented.");
        }
    }
}
把 PellokService 專案加入解決方案
dotnet sln add ./PellokService/PellokService.csproj
創建 xUnit 專案
dotnet new xunit -o PellokService.Tests

將 xUnit 測試方案加入解決方案
dotnet sln add ./PellokService.Tests/PellokService.Tests.csproj
將 PellokService 加入 Test5專案 參考
dotnet add ./PellokService.Tests/PellokService.Tests.csproj reference ./PellokService/PellokService.csproj  
刪除 PellokService.Tests/UnitTest1.cs
增加 PellokService.Tests/PellokService_IsPellokShould.cs
以下內容
using Xunit;
using Pellok.Services;
namespace Pellok.Service.Tests
{
    public class PellokService_IsPellokShould
    {
        private readonly PellokService _pellokService;
        public PellokService_IsPellokShould()
        {
            _pellokService = new PellokService();
        }
        [Fact]
        public void IsPellok_InputIs1_ReturnFalse()
        {
            var result = _pellokService.IsPellok(1);
            Assert.False(result, "1 should not be prime");
        }
    }
}
執行 dotnet test 。 Dotnet test命令會建立兩個專案,並執行測試
dotnet test

在增加 PellokService_IsPellokShould.cs
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void IsPrime_ValuesLessThan2_ReturnFalse(int value)
{
    var result = _pellokService.IsPellok(value);
    Assert.False(result, $"{value} should not be prime");
}

修改 PellokService.cs 程式
using System;
namespace Pellok.Services
{
    public class PellokService
    {
        public bool IsPellok(int candidate)
        {
            if (candidate < 2)
            {
                return false;
            }
            throw new NotImplementedException("Not fully implemented.");
        }
    }
}

除了上面的xUnit教學,還有Nunit 可以使用以下附上官方教學,給大家參考。
利用 NUnit 與 .NET Core 進行 C# 單元測試
參考: MSTest,NUnit 3,xUnit.net 2.0 比較
上一篇 Day19 Azure Pipelines服務 YAML 說明與設定
下一篇 Day 21 實作 Razor ASP.NET Core 中的頁面單元測試