使用 FluentAssertions 断言失败时如何在异常消息中显示变量名?

How to show the variable name on the exception message when the assertion fails using FluentAssertions?

我正在尝试使用 FluentAssertions 库创建一些断言 类。这是断言代码:

public AndConstraint<MyTaskAssertions> Work(string because = "", params object[] becauseArgs)
{
    Execute.Assertion
        .BecauseOf(because, becauseArgs)
        .WithExpectation("Expected {context:mytask} to work{reason}, ")
        .Given(() => Subject)
        .ForCondition(x => x.Works)
        .FailWith("but it doesn't");

    return new AndConstraint<MyTaskAssertions>(this);
}

这是我的测试:

var t = new MyTask {Works=false};
t.Should().Work();

一切正常,除了在异常消息中显示“mytask”而不是变量名称 t 的事实:

Expected mytask to work, but it doesn't

我已经阅读了文档中的 Extensibility 页面,我还检查了内置断言的源代码,但我仍然不确定异常消息到底缺少什么显示实际的变量名称,而不是 "context:" 占位符之后的名称。

您需要用[CustomAssertion]标记您的方法。另见 https://fluentassertions.com/introduction#subject-identification