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

I am trying to create some Assertion classes using the FluentAssertions library. This is the Assertion code:

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);
}

And this is my test:

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

Everything works fine, except for the fact that instead of the variable name t, "mytask" is displayed on the exception message:

Expected mytask to work, but it doesn't

I've read the Extensibility page on the Documentation, and I also checked the source code for the built-in assertions, but I am still not sure what exactly I am missing for the exception message to show the actual variable name instead of what is after the "context:" placeholder.

Upvotes: 1

Views: 761

Answers (1)

Dennis Doomen
Dennis Doomen

Reputation: 8899

You need to mark your method with [CustomAssertion]. See also https://fluentassertions.com/introduction#subject-identification

Upvotes: 3

Related Questions