Created
February 17, 2012 04:23
-
-
Save dtchepak/1850629 to your computer and use it in GitHub Desktop.
Custom matcher via extension method vs. base class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@OJ,
If you are comparing multiple fields then laziness is nice, as you can have a
IsSatisfied
method than just checks forAny()
, 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.