Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created February 17, 2012 04:23
Show Gist options
  • Save dtchepak/1850629 to your computer and use it in GitHub Desktop.
Save dtchepak/1850629 to your computer and use it in GitHub Desktop.
Custom matcher via extension method vs. base class
/* Simplified custom matcher example.
This shows matching args less than a specified int value.
More common use would be checking a few properties on a complex type (e.g. Car make, model, year)
*/
//Arg.Matches.LessThan(2);
public static class Extensions {
public static int LessThan(this Match match, int number) {
return match.WhenNoErrorsFrom(x => {
if (x < number) yield return "should be less than " + number; // << -- won't compile due to yield
}
}
// ==============
// vs.
// ==============
//Arg.Matches(new LessThanMatcher(2));
public class LessThanMatcher : CustomMatcher<int> {
int number;
public LessThanMatcher(int number) {
this.number = number;
}
public override IEnumerable<string> ReasonsMatchFailedFor(object arg) {
var x = (int) arg;
if (x < number) yield return "should be less than " + number;
}
}
@dtchepak
Copy link
Author

@OJ,

If you are comparing multiple fields then laziness is nice, as you can have a IsSatisfied method than just checks for Any(), whereas getting the description of the errors can do a complete enumeration.

Not a big deal, just would be nice if I could throw yield in there. Will probably end up doing something like match.AddError("blahblah"), so caller's experience is very similar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment