Rediscovering the Obvious

…stumbling in the footsteps of greatness

DelegatingMatcher

without comments

Really easy thing that I thought would be in the nMock framework somewhere, but couldn’t find: A way to call custom validation code against the matched object. With .NET2′s anonymous delegates, it was pretty easy to whip up just such a beast (with a bonus matcher thrown in for good measure):

    internal delegate bool ObjectMatcher(object o);

    internal class DelegatingMatcher : Matcher
    {

        public DelegatingMatcher( ObjectMatcher matcher )
        {
            _matcher = matcher;
        }

        private ObjectMatcher _matcher;

        public override void DescribeTo(System.IO.TextWriter writer)
        {
            writer.Write(“[DELEGATED]“);
        }

        public override bool Matches(object o)
        {
            return _matcher(o);
        }

        internal static bool NonZeroStringLengthMatcher(object o)
        {
            Assert.IsAssignableFrom(typeof(string), “Expected a string”);
            Assert.IsFalse(string.IsNullOrEmpty((string) o), “Expected contents in the string” );
            return true;
        }
    }
 

 

Usage:

            DelegatingMatcher thingMatcher = new DelegatingMatcher(new ObjectMatcher(
                delegate(object target)
                {
                    thingEntity thing= (thingEntity) target;
                    Assert.AreEqual(thingId, thing.ThingId);
                    Assert.AreEqual(newTitle, thing.Title);
                    Assert.AreEqual(contextId, thing.ContextId);
                    return true;
                }));
 

And

                 Expect.Once
                    .On(mockThingService)
                    .Method(“UpdateThing”)
                    .With(thingMatcher, new EqualMatcher(contextalValue), new EqualMatcher(false));

Written by erwilleke

October 25th, 2007 at 2:01 pm

Posted in Uncategorized

Leave a Reply