wip-3.6

2026-06-05 ⏳0.8分钟(0.3千字)

3.6 Using an assertion library to further improve test readability

3.6 使用断言库进一步提升测试可读性

One more thing you can do to improve test readability is to use an assertion library. I personally prefer Fluent Assertions (https://fluentassertions.com), but .NET has several competing libraries in this area.

还有一件可以提升测试可读性的事:使用断言库。我个人更喜欢 Fluent Assertions(https://fluentassertions.com),不过 .NET 在这个领域也有几个竞争库。

The main benefit of using an assertion library is how you can restructure the assertions so that they are more readable. Here’s one of our earlier tests:

使用断言库的主要好处在于,你可以重构断言的表达方式,让它们更容易阅读。下面是我们之前的一个测试:

[Fact]
public void Sum_of_two_numbers()
{
    var sut = new Calculator();

    double result = sut.Sum(10, 20);

    Assert.Equal(30, result);
}

Now compare it to the following, which uses a fluent assertion:

现在将它与下面使用流式断言的版本进行比较:

[Fact]
public void Sum_of_two_numbers()
{
    var sut = new Calculator();

    double result = sut.Sum(10, 20);

    result.Should().Be(30);
}

The assertion from the second test reads as plain English, which is exactly how you want all your code to read. We as humans prefer to absorb information in the form of stories. All stories adhere to this specific pattern:

第二个测试中的断言读起来像普通英语,而这正是你希望所有代码都具备的样子。作为人类,我们更喜欢以故事的形式吸收信息。所有故事都遵循这种特定模式:

[Subject] [action] [object].

For example,

例如:

Bob opened the door.

Here, Bob is a subject, opened is an action, and the door is an object. The same rule applies to code. result.Should().Be(30) reads better than Assert.Equal(30, result) precisely because it follows the story pattern. It’s a simple story in which result is a subject, should be is an action, and 30 is an object.

这里,Bob 是主语,opened 是动作,the door 是宾语。同样的规则也适用于代码。result.Should().Be(30) 之所以比 Assert.Equal(30, result) 更好读,正是因为它遵循了故事模式。这是一个简单的故事:result 是主语,should be 是动作,30 是宾语。

NOTE The paradigm of object-oriented programming (OOP) has become a success partly because of this readability benefit. With OOP, you, too, can structure the code in a way that reads like a story.

注意 面向对象编程(OOP)范式之所以取得成功,部分原因就在于这种可读性优势。借助 OOP,你也可以把代码组织成读起来像故事的形式。

The Fluent Assertions library also provides numerous helper methods to assert against numbers, strings, collections, dates and times, and much more. The only drawback is that such a library is an additional dependency you may not want to introduce to your project (although it’s for development only and won’t be shipped to production).

Fluent Assertions 库还提供了大量辅助方法,可用于针对数字、字符串、集合、日期时间等进行断言。唯一的缺点是,这样的库是一个额外依赖,你可能不想把它引入项目(尽管它只用于开发阶段,不会随生产环境发布)。