【问题标题】:How do I write CustomAssertion using FluentAssertions?如何使用 FluentAssertion 编写 CustomAssertion?
【发布时间】:2020-03-25 02:44:08
【问题描述】:

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,但它仍然无法正常工作。我缺少什么以及如何使其发挥作用?

【问题讨论】:

  • 您是否按照此处的说明进行操作fluentassertions.com/extensibility
  • 是的,但这没有帮助。我注意到命名空间的using 声明,在CustomTest.cs 中包含TestAssertions 的命名空间是灰色的(未使用)。我想这可能是线索。我设法通过静态类中的语法BeWorking(this ObjectAssertions obj, string because="", params object[] becauseArgs) 编写了自己的扩展方法。但我仍然想知道使用FluentAssertions docs 应该如何工作。
  • 是否有任何开源项目包含我正在尝试做的工作代码,或者可能你有一些它对你有用?我觉得我的代码遗漏了一些非常小的细节以使其正常工作。

标签: c# testing fluent-assertions


【解决方案1】:

实际上你做得很好:) 您缺少的最重要的事情是 Extension 类。我会引导你完成。

添加这个类:

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

像这样修复您的 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);
    }
}

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

【讨论】:

    猜你喜欢
    • 2016-06-07
    • 2015-02-02
    • 2021-10-29
    • 2019-01-10
    • 2011-09-09
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多