NMock extensions and .NET 4. Avoiding “magical” and hardcoded strings in property names

In the previous post I’ve shown how to avoid hardcoding method names while setting up NMock stubs. Now it’s time for properties.

First of all let’s see how we typically set up properties for stubs. Here is our interface:

    public interface ICalculator
    {
        int MinValue { get; }
        int MaxValue { get; }
    }

Now here is the unit test:

    [TestFixture]
    public class TestCalculator
    {
        [SetUp]
        public void SetUp()
        {
            mockery = new Mockery();
        }

        [Test]
        public void Test_Property_Stub()
        {
            int expectedMinValue = Int32.MinValue;
            int expectedMaxValue = Int32.MaxValue;

            calc = mockery.NewMock<ICalculator>();

            Stub.On(calc).GetProperty("MinValue").Will(Return.Value(expectedMinValue));
            Stub.On(calc).GetProperty("MaxValue").Will(Return.Value(expectedMaxValue));

            Assert.AreEqual(expectedMinValue, calc.MinValue);
            Assert.AreEqual(expectedMaxValue, calc.MaxValue);
        }

        private ICalculator calc;
        private Mockery mockery;
    }

As you can see we use magical string for property names while setting up stub. Let’s add following extension:

    public static class NMockExtensions
    {
        public static IMatchSyntax GetProperty<TProp>(this IMethodSyntax ms, Expression<Func<TProp>> expr)
        {
            var mexpr = expr.Body as MemberExpression;
            if (mexpr != null)
            {
                var memberInfo = mexpr.Member;
                return ms.GetProperty(memberInfo.Name);
            }

            return null;
        }
    }

Using this extension we can setup properties like following:

            Stub.On(calc).GetProperty(() => calc.MinValue).Will(Return.Value(expectedMinValue));
            Stub.On(calc).GetProperty(() => calc.MaxValue).Will(Return.Value(expectedMaxValue));

Leave a comment