当前位置: 首页 > 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.dtcms.com/a/334230.html

相关文章:

  • 深度学习——常见问题与优化改进
  • java中消息推送功能
  • Xiaothink-T6-0.15B混合架构模型深度解析
  • 3 种方式玩转网络继电器!W55MH32 实现网页 + 阿里云 + 本地控制互通
  • 架构调整决策
  • 超越Transformer:大模型架构创新的深度探索
  • 【计算机网络架构】混合型架构简介
  • Blackwell 和 Hopper 架构的 GPGPU 新功能全面综述
  • 【LeetCode每日一题】
  • Mac (三)如何设置环境变量
  • 从希格斯玻色子到 QPU:C++ 的跨维度征服
  • 代码随想录Day52:图论(孤岛的总面积、沉没孤岛、水流问题、建造最大岛屿)
  • 在ubuntu系统上离线安装jenkins的做法
  • 立体匹配中的稠密匹配和稀疏匹配
  • 8.16 pq
  • [系统架构设计师]系统质量属性与架构评估(八)
  • 解锁JavaScript性能优化:从理论到实战
  • 【完整源码+数据集+部署教程】太阳能面板污垢检测系统源码和数据集:改进yolo11-RVB-EMA
  • 地级市+省级气候政策不确定性指数(2000-2023年)-实证数据
  • ollama 自定义模型
  • imx6ull-驱动开发篇27——Linux阻塞和非阻塞 IO(上)
  • 【JS】认识并实现一个chrome扩展程序
  • 如何在 MacOS 上安装 SQL Server
  • MySQL完整重置密码流程(针对 macOS)
  • 硬核北京 | 2025世界机器人大会“破圈”,工业智能、康养科技…… 亦庄上演“机器人总动员”
  • Flink Sql 按分钟或日期统计数据量
  • 中本聪思想与Web3的困境:从理论到现实的跨越
  • 存算分离与云原生:数据平台的新基石
  • 基于Kubernetes亲和性与反亲和性的Pod调度优化实践指南
  • Linux上配置环境变量