惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园_首页
博客园 - 司徒正美
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Hugging Face - Blog
Hugging Face - Blog
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
G
Google Developers Blog
L
LangChain Blog
T
The Blog of Author Tim Ferriss
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
雷峰网
雷峰网
量子位
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ

博客园 - lightsong

A YOLOv8-based project for real-time traffic density estimation. LoRA unsloth比transformer库本身的微调有什么优点? offline-llms +++ transformer + peft 微调 Train and Fine-Tune Sentence Transformers Models Symmetric vs. Asymmetric Semantic Search Hierarchical Navigable Small Worlds (HNSW) Vision Transformer + BentoML ML Serving/编排工具 Introducing Gemma 3 270M: The compact model for hyper-efficient AI Utopia -- 企业世界模型 trustgraph semantica semantica vs graphti Industrial-Strength Natural Language Processing seata reference with springboot and other valuable demo outbox pattern with springboot Saga pattern with springboot 基于 Sentence Transformers 的具体应用案例 Vault with Keycloak as workload IAM Ontology Reasoning System ADR Claude Code的hook The AI-Native SDLC playbook Introduction to Dapper Introduction to FluentValidation Introduction to AutoFixture Understanding Return Types: IEnumerable, IReadOnlyCollection, and List Introduction to Refit Introduction to Carter
Introduction to FluentAssertions
lightsong · 2026-08-28 · via 博客园 - lightsong

Introduction to FluentAssertions

https://jdaniel1987.github.io/FluentAssertions

这是一篇非常适合转载的技术博客文章。我已经为你整理好了完整的中文翻译,并按照你的要求,将原文中缺失的代码片段补全,同时保留了图片占位符的位置,方便你直接复制到博客编辑器中。


博客文章草稿

标题: FluentAssertions 简介:编写更具表现力的 .NET 测试
作者: Jaime Daniel Delgado Ortega
发布时间: 2024年9月18日
阅读时间: 3 分钟


引言

FluentAssertions 是一个在 .NET 应用中广受欢迎的库,它允许开发者以一种更自然、更具表现力的方式编写断言。通过使用流畅的 API,你的测试代码将变得更易于阅读和维护,让你能专注于测试实际的行为,而不是陷入实现细节的泥潭。

FluentAssertions 的优势

  • 提升可读性: 流畅的 API 提供了一种更符合人类阅读习惯的断言写法。
  • 详细的失败信息: 当测试失败时,FluentAssertions 会提供清晰且信息丰富的错误消息,告诉你测试失败的具体原因。
  • 强类型断言: 它支持广泛的类型,并提供强类型检查,以便在编译时捕获错误。
  • 自定义断言: 你可以为特定的用例扩展该库,创建自己的自定义断言。
  • 丰富的功能: FluentAssertions 支持对集合、异常、对象、字符串、日期等多种类型进行断言。

使用示例

以下是将 FluentAssertions 集成到项目中的具体步骤。

1. 安装 NuGet 包

首先,通过 NuGet 将 FluentAssertions 添加到你的项目中。你可以在 Visual Studio 中操作:右键单击你的项目 -> 管理 NuGet 包... -> 浏览,搜索 "FluentAssertions",选中它并点击安装。

[图片占位:NuGet 包管理器安装 FluentAssertions 的截图]
(建议在此处插入一张显示在 Visual Studio 中搜索并安装 FluentAssertions 包的截图)

2. 基础断言

你可以使用更具可读性的 Should().Be() 来替代传统的 Assert.AreEqual,这能清晰地传达测试的意图。

[Fact]
public void BasicAssertionsExample()
{
    int result = 5 + 5;

    // 替代使用 Assert.AreEqual 或 Assert.IsTrue
    result.Should().Be(10);
}

3. 断言异常

FluentAssertions 让你可以轻松断言在特定场景下是否会抛出异常:

[Fact]
public void ExceptionAssertionsExample()
{
    Action act = () => throw new InvalidOperationException("Invalid operation");

    act.Should().Throw<InvalidOperationException>()
        .WithMessage("Invalid operation");
}

4. 断言集合

FluentAssertions 为断言集合的条件提供了强大的功能:

[Fact]
public void CollectionAssertionsExample()
{
    var fruits = new List<string> { "apple", "banana", "orange" };

    fruits.Should().Contain("apple")
          .And.HaveCount(3)
          .And.ContainInOrder("apple", "banana", "orange");
}

这个例子断言了以下几点:

  • 集合包含 "apple"。
  • 集合恰好有 3 个项目。
  • 项目按照指定的顺序出现。

5. 断言对象属性

你可以断言一个对象的属性是否具有期望的值:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

[Fact]
public void ObjectAssertionsExample()
{
    var person = new Person { Name = "John", Age = 30 };

    person.Should().BeEquivalentTo(new { Name = "John", Age = 30 });
}

BeEquivalentTo 方法特别有用,因为它可以自动比较对象的所有属性,而无需你手动逐一比较

6. 自定义断言 (可选)

你可以通过为领域特定的对象创建自定义断言来扩展 FluentAssertions。例如:

public static class CustomAssertions
{
    public static void ShouldHaveValidName(this Person person)
    {
        person.Name.Should().NotBeNullOrEmpty()
                    .And.MatchRegex("^[a-zA-Z]+$");
    }
}

[Fact]
public void CustomAssertionExample()
{
    var person = new Person { Name = "John", Age = 30 };

    person.ShouldHaveValidName();
}

7. 断言异步操作

FluentAssertions 同样支持对异步方法进行断言:

[Fact]
public async Task AsyncAssertionsExample()
{
    Func<Task> act = async () => await Task.Delay(500);

    await act.Should().CompleteWithinAsync(TimeSpan.FromSeconds(1));
}

这段代码断言了异步任务在指定的时间限制内完成。

结论

FluentAssertions 是一个功能强大且富有表现力的库,它能极大地提升单元测试的可读性。通过使用其流畅的接口,你可以编写出清晰、简洁的断言,从而获得更好的可维护性和更强大的测试套件。立即开始在你的测试中集成 FluentAssertions,让它们变得更易读、更具描述性、更强大吧!


标签: #C# #.NET #Testing #FluentAssertions

(本文根据 CC BY 4.0 许可协议发布)

出处:http://www.cnblogs.com/lightsong/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。