C#單元測試
xUnit + Moq + coverlet.collector
1.添加庫
MlyMathLib
2.編寫庫函數內容
using System;namespace MlyMathLib
{public interface IUserRepo{string GetName(int id);}public class UserService{private readonly IUserRepo _repo;public UserService(IUserRepo repo) => _repo = repo;public string Greet(int id) => $"Hello, {_repo.GetName(id)}!";}
}
3.添加單元測試
項目模板選擇 xUnit測試項目
MlyMathLibTests
注意檢查coverlet.collector 和Moq的庫引用
4.編寫測試用例
using MlyMathLib;
using Moq;namespace MlyMathLibTests
{public class UserServiceTests{private readonly Mock<IUserRepo> _repoMock = new();private readonly UserService _sut;public UserServiceTests(){_sut = new UserService(_repoMock.Object);}#region Greet[Fact]public void Greet_IdExists_ReturnsExpectedGreeting(){// Arrange_repoMock.Setup(r => r.GetName(1)).Returns("Alice");// Actvar actual = _sut.Greet(1);// AssertAssert.Equal("Hello, Alice!", actual);_repoMock.Verify(r => r.GetName(1), Times.Once);}[Theory][InlineData(0, "")][InlineData(-1, "Bob")][InlineData(int.MaxValue, "Z")]public void Greet_VariousValidIds_ReturnsCorrectGreeting(int id, string name){// Arrange_repoMock.Setup(r => r.GetName(id)).Returns(name);// Act & AssertAssert.Equal($"Hello, {name}!", _sut.Greet(id));}[Fact]public void Greet_RepoReturnsNull_ReturnsHelloNull(){// Arrange_repoMock.Setup(r => r.GetName(42)).Returns((string?)null);// Actvar actual = _sut.Greet(42);// AssertAssert.Equal("Hello, !", actual); // 實際輸出:Hello, !}#endregion}
}
5.運行項目
如果沒報錯,終端會出現控制臺和輸出內容
6.生成報告(覆蓋率)
打開終端
依次運行命令
注意:路徑和反斜杠問題
# 1. 運行測試并收集覆蓋率(生成 cobertura 格式的 xml)
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults# 2. 安裝 ReportGenerator(全局只需一次)
dotnet tool install -g dotnet-reportgenerator-globaltool# 3. 把 xml 轉成漂亮的 HTML
reportgenerator \-reports:"TestResults/*/coverage.cobertura.xml" \-targetdir:"coverage-html" \-reporttypes:"Html;Cobertura" \-title:"DemoLib 單元測試報告"# 4. 打開報告(Windows 用 start,macOS 用 open,Linux 用 xdg-open)
start coverage-html/index.html # Windows
# open coverage-html/index.html # macOS
# xdg-open coverage-html/index.html # Linux
實際命令
dotnet test --collect:"XPlat Code Coverage"
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults
dotnet tool install -g dotnet-reportgenerator-globaltoolreportgenerator -reports:"TestResults\60fe6df2-8246-45b8-81ef-cd4d267aa97c\coverage.cobertura.xml" -targetdir:"coverage-html" -reporttypes:"Html;Cobertura" -title:"DemoLib"
reportgenerator -reports:“TestResults\89f052dd-c413-470d-be24-832e2d53251e\coverage.cobertura.xml” -targetdir:“coverage-html” -reporttypes:“Html;Cobertura” -title:“Common.Logger.Tests”
7.生成報告(是否通過)
使用 dotnet test 生成測試報告
運行以下命令,生成測試報告:
dotnet test --logger "trx;LogFileName=test-results.trx"
這會在當前目錄下生成一個 test-results.trx 文件,該文件是一個 XML 格式的測試報告,包含了每個測試的通過/失敗情況。
extentreports-dotnet-cli
Trxer
Usage
Trxer is an EXE file.
Trxer.exe <file.trx>
The output will be at the trx folder under the name “file.trx.html”
TrxerConsole.exe <TRX file>
下載項目 重新編譯
https://github.com/NivNavick/trxer