如何使用 FluentAssertions 编写 CustomAssertion?

How do I write CustomAssertion using FluentAssertions?

FluentAssertions docs 有关于如何创建 CustomAssertion 的官方示例,但是我尝试应用它失败了。这是代码:

public abstract class BaseTest
{
    public List<int> TestList = new List<int>() { 1, 2, 3 };
}

public class Test : BaseTest { }


public class TestAssertions
{
    private readonly BaseTest test;

    public TestAssertions(BaseTest test)
    {
        this.test = test;
    }

    [CustomAssertion]
    public void BeWorking(string because = "", params object[] becauseArgs)
    {
        foreach (int num in test.TestList)
        {
            num.Should().BeGreaterThan(0, because, becauseArgs);
        }
    }
}

public class CustomTest
{
    [Fact]
    public void TryMe()
    {
        Test test = new Test();
        test.Should().BeWorking(); // error here
    }
}

我遇到编译错误:

CS1061 'ObjectAssertions' does not contain a definition for 'BeWorking' and no accessible extension method 'BeWorking' accepting a first argument of type 'ObjectAssertions' could be found (are you missing a using directive or an assembly reference?)

我也试过将 BeWorkingTestAssertions 移动到 BaseTest 但它仍然不起作用。我缺少什么以及如何让它发挥作用?

其实你做得很好:) 您缺少的最重要的东西是扩展 class。我会引导你完成。

添加这个 class:

public static class TestAssertionExtensions
{
    public static TestAssertions Should(this BaseTest instance)
    {
        return new TestAssertions(instance);
    }
}

像这样修正你的 TestAssertions class:

public class TestAssertions : ReferenceTypeAssertions<BaseTest, TestAssertions>
{
    public TestAssertions(BaseTest instance) => Subject = instance;

    protected override string Identifier => "TestAssertion";

    [CustomAssertion]
    public AndConstraint<TestAssertions> BeWorking(string because = "", params object[] becauseArgs)
    {
        foreach (int num in Subject.TestList)
        {
            num.Should().BeGreaterThan(0, because, becauseArgs);
        }

        return new AndConstraint<TestAssertions>(this);
    }
}

您的 TryMe() 测试现在应该可以正常工作了。祝你好运。