Skip to content

Add ForConstraint also to the GivenSelector<T> #2797

@ITaluone

Description

@ITaluone

Background and motivation

Now, it isn't possible to chain a .ForConstraint() after you have a .Given(() => xxx) in the chain.

This is somewhat related to #1918...

API Proposal

public class GivenSelector<T>
{
    public GivenSelector<T> ForConstraint(OccurrenceConstraint constraint, Func<T, int> func);
}

Additionally, to support inline string interpolation (especially, if the actual count should appear without quotes) I propose another .FailWith():

public class GivenSelector<T>
{
    public ContinuationOfGiven<T> FailWith(Func<T, string> message);
}

The reason is, that you then could write

.FailWith(" {expectedOccurrence}{reason}, but found it {0}.",
       actualCount  => actualCount.Times()));

like

.FailWith(actualCount  => "{expectedOccurrence}{reason}, but found it {actualCount.Times()}.");

This could also be internal, but in case I propose it as public.

assertionChain
      .ForCondition(Subject is not null)
      .BecauseOf(because, becauseArgs)
      .FailWith("...")
      .Then
      .WithExpectation("Expected something {0}", expected,
          chain => chain
              .BecauseOf(because, becauseArgs)
              .Given(() => Subject.Collection)
              .ForCondition(collection=> collection is not null)
              .FailWith("{reason}, but...")
              .Then
              .Given(collection=> collection.Count())
              .ForConstraint(occurrenceConstraint, actualCount => actualCount ) // <--- This one here
              .FailWith(" {expectedOccurrence}{reason}, but found it {0}.",
                  actualCount  => actualCount.Times()));

Alternative Designs

A quick but dirty alternative would be to call .ForCondition() like: .ForCondition(actual => occurrenceConstraint.Assert(actual)), but this seems hacky and you don't have the registered {expectedOccurrence} context data.

Risks

Non of I can think of...
The only drawback is, that in a case like above the passed in value func is formatted, and thus a string appears with qoutes in output.

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

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions