(什么时候)使用 FluentAssertions 是个好主意?

(When) would it be a good idea to use FluentAssertions?

我正在重写一个 C# .NET 项目,目前正在计划我将如何进行测试。

阅读完所有内容后,我将安装 XUnit 框架(这是第一次——我对 MSTest 更有经验)。现在我想知道我是否应该将它与 FluentAssertions(我以前也从未使用过)结合起来,或者编写纯 XUnit 测试。

乍一看,FluentAssertions 听起来既书呆子又时髦,但我不确定它是否真的会引导我编写可读性最好的代码,以及它在复杂测试中的扩展性如何。

因此,我正在寻找您的经验和论据。 [何时](做 | 会)使用 FluentAssertions?我很好奇。

Fluent Assertions is a Nuget package I've been using consistently on my projects for about 6 years. It's extremely simple to pick-up and start using. Most people can get to grips with it within 5-10 minutes and it will make reading your unit tests a little bit easier. Fluent Assertions is free so there really isn't a party foul for trying it out. I think I've introduced Fluent Assertions to over 10 teams now and so far no one's complained. The biggest reason why most teams don't use it is just lack of exposure to it. Using a standard approach a unit test may look similar to this:

[TestMethod]  
public void Example_test()  
{  
    var actual = PerformLogic();
    var expected = true;  
    Assert.AreEqual(expected, actual);  
}  

There's nothing wrong with this test but you need to spend a second or two to understand what's going on. Instead, using FLuent Assertations you can write the same test like this:

[TestMethod]  
public void Example_test()  
{  
    var result = PerformLogic();
    result.Should().BeTrue();  
}  

Hopefully, you can see that the second example takes a lot less time to read, as it reads like a sentence rather than an Assert statement. Fundamentally, this is all Fluent Assertions is, a number of extension methods that make it easier to read your unit tests compared to Assert statements. I'm hoping you can understand why it's so easy to pick up. All you need to do is get the outcome of your test in a result variable, use the Should() exertion and then use Fluent Assertions other extensions to test for your use case. Simple!

http://www.jondjones.com/c-sharp-bootcamp/tdd/fluent-assertions/what-is-fluent-assertions-and-should-i-be-using-it

Fluent 主要是关于可读性和便利性。
如果您要编写多个单元测试,我建议您使用它。 我最近遇到了将对象 'a' 和 'b' 映射到对象 'c' 的情况,我想通过单元测试验证映射器。
因此,我创建了一个 'expectedObject',其中包含对象 'c' 映射后应包含的所有属性。
因为我没有写过比较器,也不需要比较器,所以比较对象 'c' 和 'expectedObject' 以断言它们包含相同的数据会非常麻烦。所讨论的对象包含许多属性,而这些属性又具有许多属性。

但是有了 Fluent,我可以简单地写

c.Should().BeEquivalentTo(expectedObject);

这比一连串的 Assert.AreEqual() 更容易阅读,而且在这种情况下,更重要的是,写起来也快得多。