FluentAssertions Dicctionary 介绍

Fluent Assertions 提供了的一组扩展方法,用于单元测试中的断言。比起Xunit带的断言,它使你的单元测试中的断言看起来更自然流畅。 断言风格如下:

string actual = "ABCDEFGHI";
actual.Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9);
// 必须开始于AB 并且 结束于HI 并且必须包含EF 并且 长度必须是9

记得在使用前得用Nuget安装这个包

并添加命名空间引用

using FluentAssertions;

添加自定义的验证消息

    [Fact]
    public void Test_Example1()
    {
        IEnumerable<int> numbers = new[] { 1, 2, 3 };

        numbers.Should().OnlyContain(n => n > 0); //只包含大于0的元素
        numbers.Should().HaveCount(4, "because we thought we put four items in the collection");
    }

上面我们还自定义了一个额外的消息 这样我们可以看到这样的错误

Expected numbers to contain 4 item(s) because we thought we put four items in the collection, but found 3.

Assertion Scopes

有时候我们希望一个断言失败的时候,下面的断言可以继续运行,AssertionScope()就可以帮我们达到这个效果

using FluentAssertions;
using FluentAssertions.Execution;
using Xunit;
namespace MyFirstUnitTests
{
    public class MyTestClass
    {
        [Fact]
        public void Test_Example1()
        {
            using (new AssertionScope())
            {
                5.Should().Be(10); //5必须等于10   断言失败  但是下面的这行也会继续判断
                "Actual".Should().Be("Expected"); //Actual必须是Expected 断言失败 尽管上一行断言不成功,但是这行也会继承执行
            }
        }
    }
}

最近更新的
...