Skip to content

[API Proposal]: Inline custom assertions when using BeEquivalentTo #3070

@dennisdoomen

Description

@dennisdoomen

Background and motivation

Quite often, I'm facing a situation where I use an anonymous type as the expectation in BeEquivalentTo where most of the properties have discrete values, but where there is one where I need a custom assertion. For example,

subject.Should().BeEquivalentTo(new
{
    Value = 3,
    Name = // don't care as long it is lower cased
    Number = // must be bigger than 3
});

In those cases, I need to exclude those properties and add additional assertions to the test.

API Proposal

Introduce a static class that BeEquivalentTo recognizes for using other FA APIs or passing in a lambda.

public static class Match
{
    public static Match For<T>(Action<T> assertion)
    {
    }

    public static Match For<T>(Func<T, bool> assertion)
    {
    }
}

With a custom IEquivalencyStep that recognizes this Match class

API Usage

subject.Should().BeEquivalentTo(new
{
    Value = 3,
    Name = Match.For<string>(n => n.Should().BeLowerCased()),
    Number = Match.For<int>(n => n > 3),
});

Alternative Designs

Alternative names could be

Value.ThatSatisfies<string>(n => n.Should().BeLowerCased())
Value.ThatMatches<int>(n => n > 3)

Risks

None

Are you willing to help with a proof-of-concept (as PR in that or a separate repo) first and as pull-request later on?

Yes, please assign this issue to me.

Metadata

Metadata

Assignees

Labels

api-suggestionEarly API idea and discussion, it is NOT ready for implementation

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions