当前位置: 首页 > news >正文

C#单元测试(xUnit + Moq + coverlet.collector)

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

http://www.xdnf.cn/news/1311247.html

相关文章:

  • RK3568 NPU RKNN(四):RKNN-ToolKit2性能和内存评估
  • springboot集成websocket
  • SpringBoot 集成Ollama 本地大模型
  • RH134 访问网络附加存储知识点
  • 【图论】分层图 / 拆点
  • 计算机存储器分类和层次结构详解
  • PyTorch生成式人工智能——使用MusicGen生成音乐
  • 探索粒子世界:从基础理论到前沿应用与未来展望
  • Python-深度学习(一)
  • flash通信
  • 机器学习核心概念精要:从定义到评估
  • C++STL标准模板库详解
  • sql链接的url中serverTimezone的作用
  • MQ迁移方案
  • Unity 游戏提升 Android TargetVersion 相关记录
  • 深入了解 swap:作用、局限与分区建立
  • (第十七期)HTML图像标签详解:从入门到精通
  • 解决html-to-image在 ios 上dom里面的图片不显示出来
  • [Linux] Linux交换空间管理 Linux系统启动原理
  • 8.16 pq
  • 从 Windows 到 Linux 服务器的全自动部署教程(免密登录 + 压缩 + 上传 + 启动)
  • 嵌入式硬件篇---运算放大器
  • 要想在Trae运行Java程序,该怎样配置Java环境?
  • TOGAF八步一法笔记2
  • TexStudio中的Latex,PDFLatex,XeLatex和LuaLatex的区别
  • RocketMq面试集合
  • 暴雨服务器:以定制化满足算力需求多样化
  • 小白挑战一周上架元服务——元服务开发06
  • 肖臻《区块链技术与应用》第20-22讲 - 以太坊难度调整、权益证明和智能合约
  • 415. 字符串相加