如何使用 FluentAssertions 编写 CustomAssertion?

Con*_*alo 1 c# testing fluent-assertions

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

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

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
public class CustomTest
{
    [Fact]
    public void TryMe()
    {
        Test test = new Test();
        test.Should().BeWorking(); // error here
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到编译错误:

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?)

我也尝试BeWorking从to 移动TestAssertionsBaseTest但它仍然不起作用。我缺少什么以及如何使其工作?

Kor*_*bek 5

您实际上做得非常好:) 您缺少的最重要的东西是 Extension 类。我会引导你完成。

添加这个类:

public static class TestAssertionExtensions
{
    public static TestAssertions Should(this BaseTest instance)
    {
        return new TestAssertions(instance);
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样修复您的 TestAssertions 类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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